diff --git a/src/Anubis/Backtest/BasketEngine.cs b/src/Anubis/Backtest/BasketEngine.cs
new file mode 100644
index 0000000..0734ccc
--- /dev/null
+++ b/src/Anubis/Backtest/BasketEngine.cs
@@ -0,0 +1,159 @@
+using System.Collections.Concurrent;
+using Anubis.Baskets;
+
+namespace Anubis.Backtest;
+
+///
+/// Why a basket closed and why a decision was refused or noted ( ,
+/// , ): the report counts them.
+///
+public static class BasketReasons
+{
+ // Exits.
+ public const string Target = "target";
+
+ /// The Prudente basket stop, or the replica's stop in targets in the comparison configuration.
+ public const string StopBasket = "stop_basket";
+
+ /// The 9% stop on the open loss over the balance: everything closes.
+ public const string AccountStop = "account_stop";
+
+ /// The venue's stop on one position, at most at half its margin.
+ public const string MandatoryStop = "mandatory_stop";
+
+ /// The leg left alone when the other leg's mandatory stop closed: it closes at the next execution.
+ public const string OrphanLeg = "orphan_leg";
+
+ /// The venue closed everything: the equity fell below half the initial margin of the open positions.
+ public const string Liquidation = "liquidation";
+
+ /// Still open at the end of the data, valued at the last marks.
+ public const string End = "end";
+
+ // Refusals and notes.
+ public const string GateOpenLoss = "gate_open_loss";
+ public const string PausedUntilNextDay = "paused_until_next_day";
+ public const string DailyLossBlock = "daily_loss_block";
+ public const string HalfSize = "half_size";
+ public const string BelowVenueMinimum = "below_venue_minimum";
+ public const string MarginLimit = "margin_limit";
+ /// Nine positions open on the account (plan, section 9): not the daily engine's position_limit, a weight cap.
+ public const string PositionLimit = "max_positions";
+ public const string OppositePosition = "opposite_position";
+ public const string CurrencyExposure = "currency_exposure";
+ public const string CostRule = "cost_rule";
+ public const string RvolFilter = "rvol_filter";
+ public const string CorrelationLow = "correlation_low";
+ public const string SwitchTripped = "switch_tripped";
+ public const string MaxOpenBaskets = "max_open_baskets";
+
+ /// The weekend, the daily pause or the hourly window, on bars shorter than a day.
+ public const string ClockWindow = "clock_window";
+}
+
+/// The kinds of .
+public static class BasketEventKinds
+{
+ public const string Open = "open";
+ public const string Add = "add";
+ public const string Close = "close";
+ public const string Refused = "refused";
+
+ /// Something written down without changing the decision (Fedele's cost rule, a halved size).
+ public const string Note = "note";
+}
+
+///
+/// A decision of the engine on a closed bar: an opening, an averaging, a close and why, a refusal and why. Only what the data
+/// up to allows: the look-ahead check compares them on cut data.
+///
+public sealed record BasketEvent(DateTimeOffset At, DateOnly Day, string Unit, string Kind, string Reason, int Direction);
+
+///
+/// One position of a basket from its fill to its exit: the level (0 the first), pair, side, units, the market bar, moment and
+/// price of the fill and of the exit (the last mark for one still open), why it closed, commission and financing paid (USD,
+/// negative financing a credit) and the result net of both.
+///
+public sealed record BasketPositionTrace(
+ int Level,
+ string Pair,
+ Direction Side,
+ decimal Units,
+ int EntryBar,
+ DateTimeOffset EntryAt,
+ decimal EntryPrice,
+ int? ExitBar,
+ DateTimeOffset? ExitAt,
+ decimal? ExitPrice,
+ string ExitReason,
+ decimal Commission,
+ decimal Financing,
+ decimal Result);
+
+///
+/// The trace of one basket: unit, direction (+1 bought, −1 sold), the σ of the index frozen at the opening (in the index's
+/// units: pips, or basis points of the log index), every position, the bar of the last exit (null when still open at the end)
+/// and the reason. A test computes the basket's result from it, fill by fill.
+///
+public sealed record BasketTrace(int Id, string Unit, int Direction, double Sigma, IReadOnlyList Positions, int? ExitBar, string ExitReason)
+{
+ public int Levels => Positions.Select(p => p.Level).Distinct().Count();
+}
+
+///
+/// A run of the basket engine: the run the judge reads, the trace of every basket, the decisions, and the commission and
+/// financing paid in USD (financing net of credits).
+///
+public sealed record BasketRunResult(BacktestRun Run, IReadOnlyList Traces, IReadOnlyList Events, decimal Commission, decimal Financing);
+
+///
+/// The basket engine of Phase 14 (issue #127): a research margin account in USD with independent positions, one per leg and
+/// per level, on the bars of a . A decision is taken on a closed bar and executed at the next bar's
+/// open, buying at the ask and selling at the bid; every position has the venue's mandatory stop, pays commission on both
+/// sides and financing at every rollover crossed (Wednesday's counts three); the venue liquidates the account below half the
+/// initial margin. On top, the document's rules (9% account stop on mid prices in the daily pause, 2% gate, open baskets,
+/// Rvol, correlation, three-costs rule) and, «come dal vivo», SPEC 9.2 and the margin table of the plan. One equity point a
+/// day. Pure: no database, no clock, no input or output; one instance may run many rules at once.
+///
+public sealed class BasketEngine
+{
+ /// Changes when the engine computes differently: basket plans record it in their engine field.
+ public const string Version = "basket-1";
+
+ /// The symbol of the notes about the whole account (account stop, liquidation).
+ public const string AccountSymbol = "conto";
+
+ private readonly ConcurrentDictionary> _cache = new(StringComparer.Ordinal);
+
+ public BasketEngine(BasketMarket market, VenueCosts costs, decimal initialCapital)
+ {
+ ArgumentNullException.ThrowIfNull(market);
+ ArgumentNullException.ThrowIfNull(costs);
+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(initialCapital);
+ Market = market;
+ Costs = costs;
+ InitialCapital = initialCapital;
+ }
+
+ public BasketMarket Market { get; }
+
+ public VenueCosts Costs { get; }
+
+ public decimal InitialCapital { get; }
+
+ ///
+ /// One run of with costs multiplied by (spread, commission and
+ /// financing paid), trading and measuring the days from to (both included;
+ /// null: the whole market). Bars before only warm the signals up.
+ ///
+ public BasketRunResult Run(BasketRules rules, decimal costMultiplier = 1m, DateOnly? from = null, DateOnly? to = null)
+ {
+ ArgumentNullException.ThrowIfNull(rules);
+ rules.Validate();
+ return new BasketSimulation(this, rules, costMultiplier, from, to).Run();
+ }
+
+ /// A value computed once per engine and key (the signals of a unit): immutable, shared by every run.
+ internal T Cached(string key, Func compute)
+ where T : class => (T)_cache.GetOrAdd(key, _ => new Lazy(() => compute())).Value;
+}
diff --git a/src/Anubis/Backtest/BasketMarket.cs b/src/Anubis/Backtest/BasketMarket.cs
new file mode 100644
index 0000000..5a5952e
--- /dev/null
+++ b/src/Anubis/Backtest/BasketMarket.cs
@@ -0,0 +1,252 @@
+using Anubis.Baskets;
+using Anubis.Data;
+
+namespace Anubis.Backtest;
+
+/// Open, high, low and close of one side of a series on the market clock: not a number where it has no bar.
+internal sealed class PriceColumns(double[] open, double[] high, double[] low, double[] close)
+{
+ public double[] Open { get; } = open;
+
+ public double[] High { get; } = high;
+
+ public double[] Low { get; } = low;
+
+ public double[] Close { get; } = close;
+
+ public PriceColumns Slice(int count) => new(Open[..count], High[..count], Low[..count], Close[..count]);
+}
+
+///
+/// The prices the basket engine trades on (Phase 14): the bars of a without the moments where no
+/// symbol has a bar, the bid of every symbol and its ask when the source gives one. Each bar belongs to a day, the day of its
+/// equity point: the UTC date for bars of a day or longer, the server day (17:00 New York to 17:00 New York) of its close
+/// otherwise. Built once and never changed.
+///
+public sealed class BasketMarket
+{
+ private readonly DateTimeOffset[] _clock;
+ private readonly DateOnly[] _days;
+ private readonly Dictionary _bids;
+ private readonly Dictionary _asks;
+
+ private BasketMarket(string timeframe, DateTimeOffset[] clock, Dictionary bids, Dictionary asks, string fingerprint)
+ {
+ Timeframe = timeframe;
+ Length = Timeframes.Length(timeframe);
+ _clock = clock;
+ _bids = bids;
+ _asks = asks;
+ Fingerprint = fingerprint;
+ Symbols = [.. bids.Keys.Order(StringComparer.Ordinal)];
+ _days = [.. clock.Select(DayOf)];
+ }
+
+ public string Timeframe { get; }
+
+ public TimeSpan Length { get; }
+
+ /// Bars of a day or longer: the time-of-day windows of the document do not apply to them.
+ public bool Daily => Length >= TimeSpan.FromDays(1);
+
+ /// The opening moments of the bars, oldest first, in UTC.
+ public IReadOnlyList Clock => _clock;
+
+ public int Count => _clock.Length;
+
+ /// The symbols, in ordinal order.
+ public IReadOnlyList Symbols { get; }
+
+ /// The fingerprint of the data the market was built from ( ), marked when cut or flipped.
+ public string Fingerprint { get; }
+
+ /// The market of a dataset: the moments where no symbol has a bar are left out.
+ public static BasketMarket Of(BarDataset data)
+ {
+ ArgumentNullException.ThrowIfNull(data);
+ var kept = Enumerable.Range(0, data.Clock.Count).Where(t => data.Symbols.Any(s => data.Has(s, t))).ToArray();
+ PriceColumns Columns(BarColumns columns) => new(
+ [.. kept.Select(t => columns.Open[t])],
+ [.. kept.Select(t => columns.High[t])],
+ [.. kept.Select(t => columns.Low[t])],
+ [.. kept.Select(t => columns.Close[t])]);
+
+ var bids = data.Symbols.ToDictionary(s => s, s => Columns(data.Bars(s)), StringComparer.Ordinal);
+ var asks = new Dictionary(StringComparer.Ordinal);
+ foreach (var symbol in data.Symbols)
+ {
+ if (data.Ask(symbol) is { } ask)
+ {
+ asks[symbol] = Columns(ask);
+ }
+ }
+
+ return new BasketMarket(data.Timeframe, [.. kept.Select(t => data.Clock[t])], bids, asks, data.Fingerprint());
+ }
+
+ public bool Has(string symbol) => _bids.ContainsKey(symbol);
+
+ /// Whether the symbol has a bar at position .
+ public bool Has(string symbol, int t) => _bids.TryGetValue(symbol, out var columns) && !double.IsNaN(columns.Close[t]);
+
+ /// Whether the source gives the ask of the symbol: otherwise bid and ask are built around one reference price.
+ public bool HasAsk(string symbol) => _asks.ContainsKey(symbol);
+
+ /// When the bar at closes.
+ public DateTimeOffset ClosesAt(int t) => _clock[t] + Length;
+
+ /// The day of the equity point the bar at belongs to.
+ public DateOnly Day(int t) => _days[t];
+
+ ///
+ /// The reference closes of a symbol: the mid between bid and ask when both exist, the single price otherwise. Not a number
+ /// where the symbol has no bar.
+ ///
+ public IReadOnlyList Reference(string symbol)
+ {
+ var bid = Bid(symbol);
+ if (Ask(symbol) is not { } ask)
+ {
+ return bid.Close;
+ }
+
+ return [.. bid.Close.Select((b, t) => (b + ask.Close[t]) / 2)];
+ }
+
+ /// The bars that have closed by : what a decision taken then could know.
+ public BasketMarket Through(DateTimeOffset moment)
+ {
+ var count = 0;
+ while (count < _clock.Length && ClosesAt(count) <= moment)
+ {
+ count++;
+ }
+
+ return new BasketMarket(
+ Timeframe,
+ _clock[..count],
+ _bids.ToDictionary(p => p.Key, p => p.Value.Slice(count), StringComparer.Ordinal),
+ _asks.ToDictionary(p => p.Key, p => p.Value.Slice(count), StringComparer.Ordinal),
+ $"{Fingerprint}|through:{moment.UtcDateTime:yyyy-MM-dd'T'HH:mm:ss'Z'}");
+ }
+
+ ///
+ /// The surrogate of the control against chance ( ): every price of a bar is rebuilt from the close
+ /// before it with its log change turned by the sign of the bar's day (around the mean change of the series when
+ /// ). On a −1 day high and low swap, and so do bid and ask, so the ask stays above the bid. The
+ /// size of every change of the reference close is kept; all the pairs turn together, so the crosses stay consistent.
+ ///
+ public BasketMarket Surrogate(DaySigns signs, bool centred)
+ {
+ ArgumentNullException.ThrowIfNull(signs);
+ var bids = new Dictionary(StringComparer.Ordinal);
+ var asks = new Dictionary(StringComparer.Ordinal);
+ foreach (var symbol in Symbols)
+ {
+ var (bid, ask) = Flip(Bid(symbol), Ask(symbol), signs, centred);
+ bids[symbol] = bid;
+ if (ask is not null)
+ {
+ asks[symbol] = ask;
+ }
+ }
+
+ return new BasketMarket(Timeframe, _clock, bids, asks, $"{Fingerprint}|surrogate");
+ }
+
+ internal PriceColumns Bid(string symbol) =>
+ _bids.TryGetValue(symbol, out var columns) ? columns : throw new KeyNotFoundException($"{symbol} non è nei dati.");
+
+ internal PriceColumns? Ask(string symbol) => _asks.GetValueOrDefault(symbol);
+
+ private DateOnly DayOf(DateTimeOffset opensAt) => Length >= TimeSpan.FromDays(1)
+ ? DateOnly.FromDateTime(opensAt.UtcDateTime)
+ : ServerClock.Day(opensAt + Length - TimeSpan.FromTicks(1));
+
+ private (PriceColumns Bid, PriceColumns? Ask) Flip(PriceColumns bid, PriceColumns? ask, DaySigns signs, bool centred)
+ {
+ var n = _clock.Length;
+ var reference = bid.Close;
+ var mean = 0d;
+ if (centred)
+ {
+ var (sum, count, previous) = (0d, 0, double.NaN);
+ foreach (var close in reference.Where(c => !double.IsNaN(c)))
+ {
+ if (!double.IsNaN(previous))
+ {
+ sum += Math.Log(close / previous);
+ count++;
+ }
+
+ previous = close;
+ }
+
+ mean = count > 0 ? sum / count : 0;
+ }
+
+ PriceColumns Empty() => new(Nan(n), Nan(n), Nan(n), Nan(n));
+ var newBid = Empty();
+ var newAsk = ask is null ? null : Empty();
+ var before = double.NaN;
+ var made = double.NaN;
+ for (var t = 0; t < n; t++)
+ {
+ if (double.IsNaN(reference[t]))
+ {
+ continue;
+ }
+
+ if (double.IsNaN(before))
+ {
+ Copy(bid, newBid, t);
+ if (ask is not null)
+ {
+ Copy(ask, newAsk!, t);
+ }
+
+ before = reference[t];
+ made = reference[t];
+ continue;
+ }
+
+ var sign = signs[_days[t]];
+ double Price(double p) => made * Math.Exp(centred ? mean + (sign * (Math.Log(p / before) - mean)) : sign * Math.Log(p / before));
+ void Set(PriceColumns from, PriceColumns to)
+ {
+ to.Open[t] = Price(from.Open[t]);
+ to.Close[t] = Price(from.Close[t]);
+ (to.High[t], to.Low[t]) = sign > 0 ? (Price(from.High[t]), Price(from.Low[t])) : (Price(from.Low[t]), Price(from.High[t]));
+ }
+
+ if (ask is null || sign > 0)
+ {
+ Set(bid, newBid);
+ if (ask is not null)
+ {
+ Set(ask, newAsk!);
+ }
+ }
+ else
+ {
+ Set(ask, newBid);
+ Set(bid, newAsk!);
+ }
+
+ made = Price(reference[t]);
+ before = reference[t];
+ }
+
+ return (newBid, newAsk);
+ }
+
+ private static void Copy(PriceColumns from, PriceColumns to, int t) =>
+ (to.Open[t], to.High[t], to.Low[t], to.Close[t]) = (from.Open[t], from.High[t], from.Low[t], from.Close[t]);
+
+ private static double[] Nan(int n)
+ {
+ var values = new double[n];
+ Array.Fill(values, double.NaN);
+ return values;
+ }
+}
diff --git a/src/Anubis/Backtest/BasketRules.cs b/src/Anubis/Backtest/BasketRules.cs
new file mode 100644
index 0000000..9d14523
--- /dev/null
+++ b/src/Anubis/Backtest/BasketRules.cs
@@ -0,0 +1,233 @@
+using System.Globalization;
+using Anubis.Baskets;
+
+namespace Anubis.Backtest;
+
+///
+/// The two ways the basket engine runs (plan, Phase 14): «alla lettera», the document's rules alone; «come dal vivo», the
+/// same plus the limits of SPEC 9.2 and of the plan's margin table. Verdicts come only from «come dal vivo» (ADR 0026).
+///
+public enum BasketMode
+{
+ /// «alla lettera»: the rules of the research document only.
+ AsDocument,
+
+ /// «come dal vivo»: the document's rules and every limit the live bot would have.
+ AsLive,
+}
+
+/// The names of the modes in plans and reports.
+public static class BasketModes
+{
+ public const string AsDocument = "alla_lettera";
+
+ public const string AsLive = "come_dal_vivo";
+
+ public static string Name(BasketMode mode) => mode == BasketMode.AsDocument ? AsDocument : AsLive;
+
+ /// The mode a plan names; throws, in Italian, on an unknown name.
+ public static BasketMode Parse(string name) => name switch
+ {
+ AsDocument => BasketMode.AsDocument,
+ AsLive => BasketMode.AsLive,
+ _ => throw new ArgumentException($"Modalità sconosciuta: «{name}». Quelle possibili sono {AsDocument} e {AsLive}.", nameof(name)),
+ };
+}
+
+/// When a decision taken on a closed bar is executed.
+public enum BasketExecution
+{
+ /// At the next bar's open, buying at the ask and selling at the bid (the plan's convention).
+ NextOpen,
+
+ /// At the same close: only the comparison configuration with the replica of appendix G.
+ SameClose,
+}
+
+/// The index the z-score reads (sections 4.3 and 11.3).
+public enum BasketSignal
+{
+ /// The pip index X = A / pip(A) + s · B / pip(B).
+ ZScorePipSum,
+
+ /// The log index X = 10,000 · (ln A + s · ln B), in basis points.
+ ZScoreLog,
+}
+
+/// The unit of target and averaging distance: pips, or σ of the index frozen at the opening (section 11.3).
+public enum BasketMeasure
+{
+ Pips,
+ Sigma,
+}
+
+/// When a basket reaches its target.
+public enum BasketExitRule
+{
+ /// Section 4.5: the pips of every open order, added, reach the target.
+ PipSum,
+
+ /// Appendix G.3: the index is beyond the mean of the entries by the target.
+ MeanOfEntries,
+}
+
+///
+/// What a basket trades: one pair (generation B) or two legs (generation A), with the kind of their relation. The sign s of the
+/// index is +1 for a chain, −1 for a ratio, −sign(ρ) for a disjoint couple, read when the basket opens.
+///
+public sealed record BasketUnit(string Name, FxPair A, FxPair? B, RelationKind Kind)
+{
+ public static BasketUnit OnePair(FxPair pair)
+ {
+ ArgumentNullException.ThrowIfNull(pair);
+ return new BasketUnit(pair.Name, pair, null, RelationKind.SingleSymbol);
+ }
+
+ public static BasketUnit Of(FxPair a, FxPair b)
+ {
+ var relation = Relations.Classify(a, b);
+ if (relation.Kind is not (RelationKind.Chain or RelationKind.Ratio or RelationKind.Disjoint))
+ {
+ throw new ArgumentException($"{a.Name}/{b.Name}: relazione non prevista dal motore a panieri.", nameof(b));
+ }
+
+ return new BasketUnit($"{a.Name}/{b.Name}", a, b, relation.Kind);
+ }
+
+ public bool TwoLegs => B is not null;
+
+ public IReadOnlyList Legs => B is null ? [A] : [A, B];
+
+ /// The fixed sign of the index, or null for a disjoint couple (its sign comes from the correlation).
+ public int? FixedSign => Kind switch
+ {
+ RelationKind.SingleSymbol => 1,
+ RelationKind.Disjoint => null,
+ _ => Relations.Sign(Kind, null),
+ };
+}
+
+///
+/// The rules of one run of the basket engine: what is traded, the signal, levels and exit, the profile, the size, the mode and
+/// the protections. The defaults are the document's (section 4 and appendix E): Moderato, Fedele, 10 and 40 pips, leverage 5.
+///
+public sealed record BasketRules(IReadOnlyList Units)
+{
+ public BasketSignal Signal { get; init; } = BasketSignal.ZScorePipSum;
+
+ /// Bars of the z-score and σ window, bar t included.
+ public int Window { get; init; } = BasketIndex.DefaultWindow;
+
+ public double EntryZ { get; init; } = 2.0;
+
+ public BasketMeasure Measure { get; init; } = BasketMeasure.Pips;
+
+ /// The target, in pips or in σ.
+ public decimal Target { get; init; } = 10m;
+
+ /// The smallest averaging distance from the last level, in pips or in σ.
+ public decimal Distance { get; init; } = 40m;
+
+ /// The growth of the distance at each averaging (1.3 in the growing variant).
+ public decimal Growth { get; init; } = 1m;
+
+ public int MaxAveragings { get; init; } = 3;
+
+ public BasketExitRule Exit { get; init; } = BasketExitRule.PipSum;
+
+ public BasketProfile Profile { get; init; } = BasketProfiles.Fedele;
+
+ public int MaxOpenBaskets { get; init; } = 2;
+
+ /// Lots per 10,000 of initial capital, the same on every leg and every level.
+ public decimal LotPer10k { get; init; } = 0.01m;
+
+ /// The leverage of each position, never above the pair's on the real account.
+ public int Leverage { get; init; } = 5;
+
+ public BasketMode Mode { get; init; } = BasketMode.AsLive;
+
+ public BasketExecution Execution { get; init; } = BasketExecution.NextOpen;
+
+ /// The document's account rules (9% stop, 2% gate, open baskets, cost rule): off only for the comparison configuration.
+ public bool Protections { get; init; } = true;
+
+ /// The basket stop of the replica, in targets: comparison configuration only.
+ public double? StopTargets { get; init; }
+
+ /// The correlation a two-leg unit needs on its expected sign to open; null turns the check off.
+ public double? MinCorrelation { get; init; } = 0.6;
+
+ /// Above this Rvol no basket opens; null turns the filter and the distance factor off.
+ public double? MaxRvol { get; init; } = BasketIndex.DefaultMaxRvol;
+
+ /// A unit opens only if its target is at least this many times its round-trip cost (section 11.3).
+ public decimal CostMultiple { get; init; } = BasketMath.CostMultiple;
+
+ /// The hourly window 10:00–20:00 server time on bars shorter than a day (on in generation B).
+ public bool Session { get; init; }
+
+ /// The weekend, the daily pause and the hourly window on bars shorter than a day: on unless a test turns them off.
+ public bool ClockWindows { get; init; } = true;
+
+ /// Differences in the short window of Rvol.
+ public int ShortBars { get; init; } = BasketIndex.DefaultShortBars;
+
+ /// Bars of the Rvol baseline; null: 20 market days of the timeframe (20 bars on daily bars).
+ public int? BaselineBars { get; init; }
+
+ /// A test hook: the signal of bar t reads bar t + shift. Never set outside the look-ahead test.
+ internal int SignalShift { get; init; }
+
+ ///
+ /// The comparison configuration with the replica of appendix G (plan, Phase 14): generation B on one pair, z of the log
+ /// price, σ units, exit on the mean of the entries, the replica's stop in targets, decision and execution on the same
+ /// close, no protection, no filter, any number of baskets. Run it with .
+ ///
+ public static BasketRules Comparison(FxPair pair, ReplicaSettings settings)
+ {
+ ArgumentNullException.ThrowIfNull(settings);
+ settings.Validate();
+ return new BasketRules([BasketUnit.OnePair(pair)])
+ {
+ Signal = BasketSignal.ZScoreLog,
+ Window = settings.Window,
+ EntryZ = settings.EntryZ,
+ Measure = BasketMeasure.Sigma,
+ Target = (decimal)settings.TargetSigma,
+ Distance = (decimal)settings.DistanceSigma,
+ Growth = (decimal)settings.Growth,
+ MaxAveragings = settings.MaxAveragings,
+ Exit = BasketExitRule.MeanOfEntries,
+ MaxOpenBaskets = int.MaxValue,
+ Mode = BasketMode.AsDocument,
+ Execution = BasketExecution.SameClose,
+ Protections = false,
+ StopTargets = settings.StopTargets,
+ MinCorrelation = null,
+ MaxRvol = null,
+ ClockWindows = false,
+ };
+ }
+
+ /// Checks the values; the message is for the user.
+ public void Validate()
+ {
+ if (Units.Count == 0)
+ {
+ throw new ArgumentException("Le regole dei panieri non hanno nessuno strumento da seguire.");
+ }
+
+ if (Window < 3 || !(EntryZ > 0) || Target <= 0m || Distance < 0m || Growth <= 0m || MaxAveragings < 0 || MaxOpenBaskets < 1
+ || LotPer10k <= 0m || Leverage < 1 || ShortBars < 2 || BaselineBars is < 1 || StopTargets is <= 0 || MinCorrelation is < -1 or > 1)
+ {
+ throw new ArgumentException(string.Create(CultureInfo.InvariantCulture,
+ $"Regole dei panieri non valide: finestra {Window}, ingresso {EntryZ}, obiettivo {Target}, distanza {Distance}, crescita {Growth}, mediazioni {MaxAveragings}, panieri {MaxOpenBaskets}, lotto {LotPer10k}, leva {Leverage}."));
+ }
+
+ if (Units.Select(u => u.Name).Distinct(StringComparer.Ordinal).Count() != Units.Count)
+ {
+ throw new ArgumentException("Le regole dei panieri nominano due volte lo stesso strumento.");
+ }
+ }
+}
diff --git a/src/Anubis/Backtest/BasketSignals.cs b/src/Anubis/Backtest/BasketSignals.cs
new file mode 100644
index 0000000..feae10f
--- /dev/null
+++ b/src/Anubis/Backtest/BasketSignals.cs
@@ -0,0 +1,100 @@
+using Anubis.Baskets;
+
+namespace Anubis.Backtest;
+
+///
+/// The compressed series of a unit (Phase 14): only the bars where every leg has a close, so a holiday of one pair never puts
+/// a gap in a window. maps a bar of the market to its place in the series (−1 when a leg is missing).
+/// The prices are the reference closes: mid when bid and ask exist, the single price otherwise.
+///
+internal sealed class UnitData
+{
+ public UnitData(BasketMarket market, BasketUnit unit)
+ {
+ Unit = unit;
+ var legs = unit.Legs.Select(l => l.Name).ToArray();
+ var position = new int[market.Count];
+ Array.Fill(position, -1);
+ var bars = new List(market.Count);
+ for (var t = 0; t < market.Count; t++)
+ {
+ if (legs.All(l => market.Has(l, t)))
+ {
+ position[t] = bars.Count;
+ bars.Add(t);
+ }
+ }
+
+ Bars = [.. bars];
+ Position = position;
+ var a = market.Reference(unit.A.Name);
+ PricesA = [.. Bars.Select(t => a[t])];
+ if (unit.B is not null)
+ {
+ var b = market.Reference(unit.B.Name);
+ PricesB = [.. Bars.Select(t => b[t])];
+ }
+ }
+
+ public BasketUnit Unit { get; }
+
+ /// The market bar of each point of the series.
+ public int[] Bars { get; }
+
+ /// The point of the series of each market bar, −1 when a leg has no bar.
+ public int[] Position { get; }
+
+ public double[] PricesA { get; }
+
+ public double[]? PricesB { get; }
+
+ /// The index of the signal at prices and with sign .
+ public double Index(BasketSignal signal, int sign, double a, double b) => (signal, Unit.B) switch
+ {
+ (BasketSignal.ZScorePipSum, null) => BasketIndex.Pips(a, Unit.A),
+ (BasketSignal.ZScorePipSum, { } legB) => BasketIndex.Pips(a, Unit.A, b, legB, sign),
+ (_, null) => BasketIndex.LogBp(a),
+ _ => BasketIndex.LogBp(a, b, -sign),
+ };
+
+ /// The pip index, whatever the signal: targets and distances in pips with the exit on the mean of the entries read it.
+ public double PipIndex(int sign, double a, double b) => Index(BasketSignal.ZScorePipSum, sign, a, b);
+
+ /// The correlation of the log returns of the two legs over the window ending at point ; null for one leg.
+ public double? Correlation(int c, int window) => PricesB is null ? null : BasketIndex.Correlation(PricesA, PricesB, c, window);
+}
+
+///
+/// The signals of a unit with one index and one sign: the index, z and σ from the shared rolling functions of the replica
+/// ( , ), Rvol ( )
+/// when the filter is on, and the pip index. One value per point of the compressed series.
+///
+internal sealed class UnitSignal
+{
+ public UnitSignal(UnitData data, BasketSignal signal, int sign, int window, int? baselineBars, int shortBars)
+ {
+ var n = data.Bars.Length;
+ Index = new double[n];
+ Pips = new double[n];
+ for (var c = 0; c < n; c++)
+ {
+ var b = data.PricesB?[c] ?? 0;
+ Index[c] = data.Index(signal, sign, data.PricesA[c], b);
+ Pips[c] = data.PipIndex(sign, data.PricesA[c], b);
+ }
+
+ Z = BasketIndex.RollingZ(Index, window);
+ Sigma = BasketIndex.RollingSigma(Index, window);
+ Rvol = baselineBars is { } baseline ? BasketIndex.RollingRvol(Index, baseline, shortBars) : null;
+ }
+
+ public double[] Index { get; }
+
+ public double[] Pips { get; }
+
+ public double[] Z { get; }
+
+ public double[] Sigma { get; }
+
+ public double[]? Rvol { get; }
+}
diff --git a/src/Anubis/Backtest/BasketSimulation.cs b/src/Anubis/Backtest/BasketSimulation.cs
new file mode 100644
index 0000000..1ba3e24
--- /dev/null
+++ b/src/Anubis/Backtest/BasketSimulation.cs
@@ -0,0 +1,1194 @@
+using System.Globalization;
+using Anubis.Baskets;
+using Anubis.Risk;
+using Anubis.Trading;
+
+namespace Anubis.Backtest;
+
+///
+/// One run of the : the account, the open baskets and the orders waiting for the next open, walked
+/// bar by bar. Each bar: at the open, the mandatory stops a gap went through, then the orders decided at the previous close
+/// (closes first); during the bar, the mandatory stops the low or the high touched; at the close, financing, the marks,
+/// liquidation, the account stop, SPEC 9.2 «come dal vivo», then the decisions (exits, averagings, new baskets), and the
+/// equity point when the day ends.
+///
+internal sealed class BasketSimulation
+{
+ private readonly BasketEngine _engine;
+ private readonly BasketMarket _market;
+ private readonly BasketRules _rules;
+ private readonly VenueCosts _costs;
+ private readonly decimal _multiplier;
+ private readonly DateOnly _from;
+ private readonly DateOnly _to;
+ private readonly Unit[] _units;
+ private readonly Dictionary _lastBar = new(StringComparer.Ordinal);
+ private readonly bool _live;
+ private readonly double _target;
+ private readonly double _distance;
+ private readonly double _growth;
+
+ private readonly List _positions = [];
+ private readonly List _baskets = [];
+ private readonly List _pending = [];
+ private readonly List _equity = [];
+ private readonly List _equityAt = [];
+ private readonly List _fills = [];
+ private readonly List _notes = [];
+ private readonly List _events = [];
+
+ private decimal _cash;
+ private decimal _commission;
+ private decimal _financing;
+ private int _nextId;
+ private DateTimeOffset? _pausedUntil;
+ private RiskMonitorState _risk = RiskMonitorState.Initial;
+ private RiskMeasures _measures = RiskMeasures.None;
+ private decimal? _peak;
+ private int _last = -1;
+
+ public BasketSimulation(BasketEngine engine, BasketRules rules, decimal multiplier, DateOnly? from, DateOnly? to)
+ {
+ _engine = engine;
+ _market = engine.Market;
+ _rules = rules;
+ _multiplier = multiplier;
+ _costs = engine.Costs.Scaled(multiplier);
+ _cash = engine.InitialCapital;
+ _live = rules.Mode == BasketMode.AsLive;
+ _target = (double)rules.Target;
+ _distance = (double)rules.Distance;
+ _growth = (double)rules.Growth;
+ _from = from ?? (_market.Count > 0 ? _market.Day(0) : DateOnly.MinValue);
+ _to = to ?? (_market.Count > 0 ? _market.Day(_market.Count - 1) : DateOnly.MaxValue);
+
+ // Units whose legs are not all in the data are not traded; the conversions to dollars are checked when first needed.
+ _units = [.. rules.Units
+ .Where(u => u.Legs.All(l => _market.Has(l.Name)))
+ .Select((u, i) => new Unit(i, u, engine.Cached($"unit|{u.Name}", () => new UnitData(_market, u))))];
+ }
+
+ private int Leverage(FxPair pair) => Math.Min(_rules.Leverage, _costs.Pair(pair.Name).MaxLeverage);
+
+ public BasketRunResult Run()
+ {
+ for (var t = 0; t < _market.Count && _market.Day(t) <= _to; t++)
+ {
+ _last = t;
+ var active = _market.Day(t) >= _from;
+ if (_positions.Count > 0 || _pending.Count > 0)
+ {
+ Open(t);
+ During(t);
+ }
+
+ Close(t, active);
+ if (active && (t + 1 == _market.Count || _market.Day(t + 1) != _market.Day(t)))
+ {
+ var (equity, _) = Marks(t, mid: false);
+ _equity.Add(new EquityPoint(_market.Day(t), equity, _cash, Margin()));
+ _equityAt.Add(_market.ClosesAt(t));
+ }
+ }
+
+ return Finish();
+ }
+
+ // ----- the open and the bar -----
+
+ private void Open(int t)
+ {
+ // Stops a gap went through fill at the open; then the orders of the previous close, closes first. What a stop leaves
+ // behind waits for the next execution, like everything decided after the close.
+ var due = _pending.OrderBy(p => p.Kind == PendingKind.Close ? 0 : 1).ToList();
+ _pending.Clear();
+ foreach (var position in _positions.Where(p => p.Stop is not null && p.EntryBar < t && _market.Has(p.Pair.Name, t)).ToList())
+ {
+ var quote = Quote(position.Pair, t, Field.Open);
+ if (position.Side == Direction.Buy ? quote.Bid <= position.Stop : quote.Ask >= position.Stop)
+ {
+ Stopped(position, t, position.Side == Direction.Buy ? quote.Bid : quote.Ask, _market.Clock[t], Field.Open);
+ }
+ }
+
+ foreach (var order in due)
+ {
+ if (order.Kind != PendingKind.Close && order.Basket.Exit is not null)
+ {
+ continue;
+ }
+
+ if (!Execute(order, t, Field.Open))
+ {
+ _pending.Add(order);
+ }
+ }
+ }
+
+ private void During(int t)
+ {
+ foreach (var position in _positions.Where(p => p.Stop is not null && p.Open && _market.Has(p.Pair.Name, t) && !(p.EntryBar == t && p.AtClose)).ToList())
+ {
+ var touched = position.Side == Direction.Buy
+ ? Quote(position.Pair, t, Field.Low).Bid <= position.Stop
+ : Quote(position.Pair, t, Field.High).Ask >= position.Stop;
+ if (touched && position.Open)
+ {
+ Stopped(position, t, position.Stop!.Value, _market.Clock[t], Field.Close);
+ }
+ }
+ }
+
+ /// A mandatory stop: the position closes; the rest of its basket closes at the next execution.
+ private void Stopped(Position position, int t, decimal price, DateTimeOffset at, Field field)
+ {
+ var basket = position.Basket;
+ ClosePosition(position, t, price, at, field, BasketReasons.MandatoryStop);
+ _notes.Add(new BacktestNote(_market.Day(t), position.Pair.Name, BasketReasons.MandatoryStop));
+ _events.Add(Event(t, basket.Unit.Data.Unit.Name, BasketEventKinds.Close, BasketReasons.MandatoryStop, basket.Direction));
+ _pending.RemoveAll(p => p.Basket == basket && p.Kind == PendingKind.Add);
+ var rest = basket.Positions.Where(p => p.Open).ToList();
+ if (rest.Count == 0)
+ {
+ basket.Exit ??= BasketReasons.MandatoryStop;
+ Done(basket);
+ return;
+ }
+
+ if (basket.Exit is not null)
+ {
+ return;
+ }
+
+ var orphan = basket.Unit.Data.Unit.TwoLegs && rest.Any(p => p.Pair != position.Pair);
+ basket.Exit = orphan ? BasketReasons.OrphanLeg : BasketReasons.MandatoryStop;
+ if (orphan)
+ {
+ _notes.Add(new BacktestNote(_market.Day(t), rest.First(p => p.Pair != position.Pair).Pair.Name, BasketReasons.OrphanLeg));
+ }
+
+ _pending.Add(new Pending(PendingKind.Close, basket, 0m, basket.Exit));
+ }
+
+ // ----- the close -----
+
+ private void Close(int t, bool active)
+ {
+ var at = _market.ClosesAt(t);
+ foreach (var position in _positions)
+ {
+ Finance(position, at);
+ }
+
+ if (_rules.Execution == BasketExecution.SameClose && _pending.Count > 0)
+ {
+ foreach (var order in _pending.ToList())
+ {
+ if (Execute(order, t, Field.Close))
+ {
+ _pending.Remove(order);
+ }
+ }
+ }
+
+ if (!active)
+ {
+ return;
+ }
+
+ var (equity, margin) = Marks(t, mid: false);
+
+ // The venue's liquidation: below half the initial margin of the open positions, everything closes at this close.
+ var liquidated = _costs.LiquidationLevel is { } level && _positions.Count > 0 && equity < level * margin;
+ if (liquidated)
+ {
+ CloseAll(t, BasketReasons.Liquidation, Field.Close);
+ (equity, _) = Marks(t, mid: false);
+ }
+
+ if (_live)
+ {
+ StepRisk(t, equity);
+ }
+
+ if (liquidated)
+ {
+ return;
+ }
+
+ // The document's account stop: open loss over the balance, on mid prices inside the daily pause.
+ if (_rules.Protections && _positions.Count > 0)
+ {
+ var (stopEquity, _) = Marks(t, mid: InPause(at));
+ if (_cash > 0m && (_cash - stopEquity) / _cash >= _rules.Profile.EquityStop)
+ {
+ _notes.Add(new BacktestNote(_market.Day(t), BasketEngine.AccountSymbol, BasketReasons.AccountStop));
+ foreach (var basket in _baskets.Where(b => !b.Finished))
+ {
+ basket.Exit = BasketReasons.AccountStop;
+ _events.Add(Event(t, basket.Unit.Data.Unit.Name, BasketEventKinds.Close, BasketReasons.AccountStop, basket.Direction));
+ }
+
+ _pending.RemoveAll(p => p.Kind != PendingKind.Close);
+ foreach (var basket in _baskets.Where(b => !b.Finished && b.Positions.Count == 0).ToList())
+ {
+ Done(basket);
+ }
+
+ if (_rules.Profile.ResumeAtNextServerDay)
+ {
+ _pausedUntil = ServerClock.NextDayStart(at);
+ }
+
+ if (_rules.Execution == BasketExecution.SameClose)
+ {
+ CloseAll(t, BasketReasons.AccountStop, Field.Close);
+ }
+ else
+ {
+ foreach (var basket in _baskets.Where(b => !b.Finished && b.Positions.Count > 0))
+ {
+ _pending.RemoveAll(p => p.Basket == basket);
+ _pending.Add(new Pending(PendingKind.Close, basket, 0m, BasketReasons.AccountStop));
+ }
+ }
+
+ return;
+ }
+ }
+
+ Decide(t, equity);
+ }
+
+ private void Decide(int t, decimal equity)
+ {
+ var at = _market.ClosesAt(t);
+ var blocked = _live && RiskMonitor.EntriesBlocked(_risk, at);
+ var multiplier = _live ? RiskMonitor.Multiplier(_risk, _measures, at, RiskLimits.Default) : 1m;
+ var openLoss = _cash > 0m ? (_cash - Marks(t, mid: InPause(at)).Equity) / _cash : 0m;
+ var paused = _pausedUntil is { } until && _market.Clock[t] < until;
+ var plan = new Plan();
+ var closedNow = new HashSet();
+
+ // Open baskets: exit first, then averaging.
+ foreach (var basket in _baskets.Where(b => !b.Finished && b.Exit is null && b.DecisionBar < t && !b.Waiting(_pending)).ToList())
+ {
+ var unit = basket.Unit;
+ var c = unit.Data.Position[t];
+ if (c < 0)
+ {
+ continue;
+ }
+
+ var signal = unit.Signal(_engine, _rules, basket.Sign);
+ if (ExitReason(basket, t, c, signal, equity) is { } reason)
+ {
+ basket.Exit = reason;
+ closedNow.Add(unit.Index);
+ _events.Add(Event(t, unit.Data.Unit.Name, BasketEventKinds.Close, reason, basket.Direction));
+ if (_rules.Execution == BasketExecution.SameClose)
+ {
+ foreach (var position in basket.Positions.Where(p => p.Open).ToList())
+ {
+ ClosePosition(position, t, Exit(position, Quote(position.Pair, t, Field.Close)), at, Field.Close, reason);
+ }
+
+ Done(basket);
+ }
+ else
+ {
+ _pending.Add(new Pending(PendingKind.Close, basket, 0m, reason));
+ }
+
+ continue;
+ }
+
+ if (!AveragingDue(basket, t, c, signal))
+ {
+ Refuse(unit, null, t, basket.Direction);
+ continue;
+ }
+
+ var refusal = paused ? BasketReasons.PausedUntilNextDay
+ : _rules.ClockWindows && !_market.Daily && ServerClock.InDailyPause(at) ? BasketReasons.ClockWindow
+ : _live && _risk.Tripped ? BasketReasons.SwitchTripped
+ : blocked ? BasketReasons.DailyLossBlock
+ : null;
+ var units = Math.Min(basket.FirstUnits, Size(unit, t, multiplier));
+ var exposed = false;
+ refusal ??= Limits(unit, basket.Direction, basket.Sign, units, t, equity, plan, out exposed);
+ if (Refuse(unit, refusal, t, basket.Direction))
+ {
+ continue;
+ }
+
+ NoteHalf(unit, t, basket.Direction, multiplier);
+ if (exposed)
+ {
+ Note(unit, t, basket.Direction, BasketReasons.CurrencyExposure);
+ }
+
+ _events.Add(Event(t, unit.Data.Unit.Name, BasketEventKinds.Add, BasketEventKinds.Add, basket.Direction));
+ Place(new Pending(PendingKind.Add, basket, units, BasketEventKinds.Add), t, plan);
+ }
+
+ // New baskets, largest |z| first.
+ var candidates = new List<(Unit Unit, int Direction, int Sign, double Z)>();
+ foreach (var unit in _units)
+ {
+ var c = unit.Data.Position[t];
+ if (c < 0 || closedNow.Contains(unit.Index) || _baskets.Any(b => !b.Finished && b.Unit == unit))
+ {
+ continue;
+ }
+
+ if (Sign(unit, c) is not { } sign)
+ {
+ Refuse(unit, null, t, 0);
+ continue;
+ }
+
+ var signal = unit.Signal(_engine, _rules, sign);
+ var z = Z(signal, c);
+ var direction = z <= -_rules.EntryZ ? 1 : z >= _rules.EntryZ ? -1 : 0;
+ if (direction == 0 || !(signal.Sigma[c] > 0))
+ {
+ Refuse(unit, null, t, 0);
+ continue;
+ }
+
+ candidates.Add((unit, direction, sign, Math.Abs(z)));
+ }
+
+ foreach (var (unit, direction, sign, _) in candidates.OrderByDescending(x => x.Z).ThenBy(x => x.Unit.Index))
+ {
+ var c = unit.Data.Position[t];
+ var signal = unit.Signal(_engine, _rules, sign);
+ var refusal = EntryGate(unit, t, c, sign, signal, paused, blocked, openLoss);
+ var costly = refusal is null && _rules.Protections && !PassesCostRule(unit, t, signal.Sigma[c]);
+ if (costly && _rules.Profile.CostGate)
+ {
+ refusal = BasketReasons.CostRule;
+ }
+
+ var units = Size(unit, t, multiplier);
+ var exposed = false;
+ refusal ??= Limits(unit, direction, sign, units, t, equity, plan, out exposed);
+ if (Refuse(unit, refusal, t, direction))
+ {
+ continue;
+ }
+
+ NoteHalf(unit, t, direction, multiplier);
+ if (costly)
+ {
+ Note(unit, t, direction, BasketReasons.CostRule);
+ }
+
+ if (exposed)
+ {
+ Note(unit, t, direction, BasketReasons.CurrencyExposure);
+ }
+
+ var basket = new Basket(_nextId++, unit, direction, sign, signal.Sigma[c], t, c, units);
+ _baskets.Add(basket);
+ _events.Add(Event(t, unit.Data.Unit.Name, BasketEventKinds.Open, BasketEventKinds.Open, direction));
+ Place(new Pending(PendingKind.Open, basket, units, BasketEventKinds.Open), t, plan);
+ }
+ }
+
+ /// The first gate a new basket meets, or null: clock, pause after the account stop, SPEC 9.2, the document's filters.
+ private string? EntryGate(Unit unit, int t, int c, int sign, UnitSignal signal, bool paused, bool blocked, decimal openLoss)
+ {
+ var at = _market.ClosesAt(t);
+ if (_rules.ClockWindows && !_market.Daily && !ServerClock.EntriesAllowed(at, _rules.Session))
+ {
+ return BasketReasons.ClockWindow;
+ }
+
+ if (paused)
+ {
+ return BasketReasons.PausedUntilNextDay;
+ }
+
+ if (_live && _risk.Tripped)
+ {
+ return BasketReasons.SwitchTripped;
+ }
+
+ if (blocked)
+ {
+ return BasketReasons.DailyLossBlock;
+ }
+
+ if (_rules.Protections && openLoss >= 0.02m)
+ {
+ return BasketReasons.GateOpenLoss;
+ }
+
+ if (_baskets.Count(b => !b.Finished) >= _rules.MaxOpenBaskets)
+ {
+ return BasketReasons.MaxOpenBaskets;
+ }
+
+ if (_rules.MaxRvol is { } max && !BasketIndex.AllowsEntry(Finite(signal.Rvol?[c]), max))
+ {
+ return BasketReasons.RvolFilter;
+ }
+
+ if (_rules.MinCorrelation is { } min && unit.Data.Unit.TwoLegs
+ && !(unit.Data.Correlation(c, _rules.Window) is { } rho && -sign * rho >= min))
+ {
+ return BasketReasons.CorrelationLow;
+ }
+
+ return null;
+ }
+
+ ///
+ /// «Come dal vivo» only: a level below the venue minimum does not start; no position against one already held on the same
+ /// instrument; net exposure per currency at most two entries (Prudente refuses, Fedele notes: );
+ /// at most nine positions; the margin committed at most 40% of the equity. Null when the level may go.
+ ///
+ private string? Limits(Unit unit, int direction, int sign, decimal units, int t, decimal equity, Plan plan, out bool exposed)
+ {
+ exposed = false;
+ if (!_live)
+ {
+ return null;
+ }
+
+ var legs = Legs(unit, direction, sign);
+ var exposures = legs.Select(l => units * UsdPer(l.Pair.Base, t, Field.Close)).ToArray();
+ if (units <= 0m || exposures.Any(e => e < _costs.MinimumUsd))
+ {
+ return BasketReasons.BelowVenueMinimum;
+ }
+
+ var held = _positions.Where(p => p.Open).Select(p => (p.Pair, p.Side)).Concat(plan.Legs.Select(l => (l.Pair, l.Side)));
+ if (legs.Any(l => held.Any(h => h.Pair == l.Pair && h.Side != l.Side)))
+ {
+ return BasketReasons.OppositePosition;
+ }
+
+ var entry = exposures.Max();
+ var all = _positions.Where(p => p.Open).Select(p => new ExposureLeg(p.Pair, p.Side, p.Units, p.EntryPrice))
+ .Concat(plan.Legs)
+ .Concat(legs.Select(l => new ExposureLeg(l.Pair, l.Side, units, Mid(l.Pair, t, Field.Close))));
+ var cap = _rules.Profile.MaxCurrencyExposure ?? 2m;
+ if (BasketMath.Exposure(all).Any(e => Math.Abs(e.Value * UsdPer(e.Key, t, Field.Close)) > cap * entry))
+ {
+ if (_rules.Profile.MaxCurrencyExposure is not null)
+ {
+ return BasketReasons.CurrencyExposure;
+ }
+
+ exposed = true;
+ }
+
+ if (_positions.Count(p => p.Open) + plan.Legs.Count + legs.Count > MaxPositions)
+ {
+ return BasketReasons.PositionLimit;
+ }
+
+ var margin = legs.Select((l, i) => exposures[i] / Leverage(l.Pair)).Sum();
+ if (Margin() + plan.Margin + margin > MaxMarginShare * equity)
+ {
+ return BasketReasons.MarginLimit;
+ }
+
+ plan.Margin += margin;
+ plan.Legs.AddRange(legs.Select(l => new ExposureLeg(l.Pair, l.Side, units, Mid(l.Pair, t, Field.Close))));
+ return null;
+ }
+
+ /// At most nine positions: the Demo shared with the user's other bot (plan, section 9).
+ private const int MaxPositions = 9;
+
+ /// The margin committed stays within 40% of the equity (plan, section 5).
+ private const decimal MaxMarginShare = 0.40m;
+
+ private string? ExitReason(Basket basket, int t, int c, UnitSignal signal, decimal equity)
+ {
+ var x = signal.Index[c];
+ var sigma = basket.Sigma;
+
+ // Prudente's basket stops, «come dal vivo».
+ var profile = _rules.Profile;
+ if (_live && profile.HasBasketStops())
+ {
+ var z = Z(signal, c);
+ if ((profile.StopZ is { } stopZ && (basket.Direction > 0 ? z <= -stopZ : z >= stopZ))
+ || (profile.StopLoss is { } stopLoss && BasketValue(basket, t) <= -stopLoss * equity)
+ || (profile.StopOnBrokenRelation && basket.Unit.Data.Unit.TwoLegs
+ && !(basket.Unit.Data.Correlation(c, _rules.Window) is { } rho && -basket.Sign * rho > 0))
+ || (profile.StopAfterBars is { } bars && c - basket.OpenedAt >= bars))
+ {
+ return BasketReasons.StopBasket;
+ }
+ }
+
+ // The replica's stop in targets: the comparison configuration.
+ if (_rules.StopTargets is { } stop && _rules.Measure == BasketMeasure.Sigma)
+ {
+ var sum = 0d;
+ foreach (var level in basket.Levels)
+ {
+ sum += basket.Direction * (x - level.Index);
+ }
+
+ if (-(sum / (_target * sigma)) >= stop)
+ {
+ return BasketReasons.StopBasket;
+ }
+ }
+
+ var reached = (_rules.Exit, _rules.Measure) switch
+ {
+ (BasketExitRule.PipSum, BasketMeasure.Pips) => basket.Positions.Where(p => p.Open)
+ .Sum(p => BasketMath.OrderPips(p.Side, p.EntryPrice, Quote(p.Pair, t, Field.Close), p.Pair.Pip)) >= _rules.Target,
+ (BasketExitRule.PipSum, _) => basket.Levels.Sum(l => basket.Direction * (x - l.Index)) >= _target * sigma,
+ (_, BasketMeasure.Sigma) => basket.Direction * (x - Mean(basket.Levels, l => l.Index)) >= _target * sigma,
+ _ => basket.Direction * (signal.Pips[c] - Mean(basket.Levels, l => l.Pips)) >= _target,
+ };
+ return reached ? BasketReasons.Target : null;
+ }
+
+ /// The averaging rule: fewer levels than allowed, the last one far enough under water, the signal still true.
+ private bool AveragingDue(Basket basket, int t, int c, UnitSignal signal)
+ {
+ var made = basket.Levels.Count - 1;
+ if (made >= _rules.MaxAveragings)
+ {
+ return false;
+ }
+
+ var factor = _rules.MaxRvol is null ? 1d : Finite(signal.Rvol?[c]) is { } rvol ? Math.Max(1, Math.Min(rvol, 3)) : 1d;
+ var far = _rules.Measure == BasketMeasure.Sigma
+ ? basket.Direction * (basket.Levels[^1].Index - signal.Index[c]) >= _distance * basket.Sigma * factor * Math.Pow(_growth, made)
+ : basket.Positions.Where(p => p.Open && p.Level == made)
+ .Sum(p => BasketMath.OrderPips(p.Side, p.EntryPrice, Quote(p.Pair, t, Field.Close), p.Pair.Pip))
+ <= -(decimal)(_distance * factor * Math.Pow(_growth, made));
+ if (!far)
+ {
+ return false;
+ }
+
+ var z = Z(signal, c);
+ return basket.Direction > 0 ? z <= -_rules.EntryZ : z >= _rules.EntryZ;
+ }
+
+ /// The three-costs rule (section 11.3): the target is at least the multiple of the basket's round trip at this close.
+ private bool PassesCostRule(Unit unit, int t, double sigma)
+ {
+ var pips = 0m;
+ var basis = 0d;
+ foreach (var leg in unit.Data.Unit.Legs)
+ {
+ var quote = Quote(leg, t, Field.Close);
+ var mid = (quote.Bid + quote.Ask) / 2;
+ var rate = _costs.Pair(leg.Name).CommissionPerSide;
+ pips += ((quote.Ask - quote.Bid) / leg.Pip) + (2 * rate * mid / leg.Pip);
+ basis += (double)(((quote.Ask - quote.Bid) / mid) + (2 * rate)) * 10_000;
+ }
+
+ if (_rules.Measure == BasketMeasure.Pips)
+ {
+ return _rules.Target >= _rules.CostMultiple * pips;
+ }
+
+ var cost = _rules.Signal == BasketSignal.ZScorePipSum ? (double)pips : basis;
+ return _target * sigma >= (double)_rules.CostMultiple * cost;
+ }
+
+ /// The units of a new level: equal on every leg from the initial capital (raised to the venue minimum), times SPEC 9.2's multiplier.
+ private decimal Size(Unit unit, int t, decimal multiplier)
+ {
+ var usd = unit.Data.Unit.Legs.Select(l => UsdPer(l.Base, t, Field.Close)).ToArray();
+ var units = BasketMath.EqualUnits(_rules.LotPer10k, _engine.InitialCapital, usd, _costs.MinimumUsd).Units;
+ return multiplier < 1m ? Math.Floor(units * multiplier) : units;
+ }
+
+ private void NoteHalf(Unit unit, int t, int direction, decimal multiplier)
+ {
+ if (multiplier < 1m)
+ {
+ Note(unit, t, direction, BasketReasons.HalfSize);
+ }
+ }
+
+ ///
+ /// Writes a refusal (one note per spell: the same refusal on the unit's next bar is not written again); null clears the
+ /// spell. True when there was a refusal.
+ ///
+ private bool Refuse(Unit unit, string? reason, int t, int direction)
+ {
+ var again = reason is not null && reason == unit.Refused;
+ unit.Refused = reason;
+ if (reason is null)
+ {
+ return false;
+ }
+
+ if (!again)
+ {
+ _notes.Add(new BacktestNote(_market.Day(t), unit.Data.Unit.Name, reason));
+ _events.Add(Event(t, unit.Data.Unit.Name, BasketEventKinds.Refused, reason, direction));
+ }
+
+ return true;
+ }
+
+ private void Note(Unit unit, int t, int direction, string reason)
+ {
+ _notes.Add(new BacktestNote(_market.Day(t), unit.Data.Unit.Name, reason));
+ _events.Add(Event(t, unit.Data.Unit.Name, BasketEventKinds.Note, reason, direction));
+ }
+
+ private void Place(Pending order, int t, Plan plan)
+ {
+ if (_rules.Execution == BasketExecution.SameClose)
+ {
+ Execute(order, t, Field.Close);
+ plan.Legs.Clear();
+ plan.Margin = 0m;
+ }
+ else
+ {
+ _pending.Add(order);
+ }
+ }
+
+ // ----- execution -----
+
+ /// Executes an order at the open or at the close of bar t; false when a leg has no price there (it waits).
+ private bool Execute(Pending order, int t, Field field)
+ {
+ var basket = order.Basket;
+ if (order.Kind == PendingKind.Close)
+ {
+ var open = basket.Positions.Where(p => p.Open).ToList();
+ if (open.Any(p => !_market.Has(p.Pair.Name, t)))
+ {
+ return false;
+ }
+
+ var at = field == Field.Open ? _market.Clock[t] : _market.ClosesAt(t);
+ foreach (var position in open)
+ {
+ ClosePosition(position, t, Exit(position, Quote(position.Pair, t, field)), at, field, order.Reason);
+ }
+
+ Done(basket);
+ return true;
+ }
+
+ var unit = basket.Unit;
+ var legs = Legs(unit, basket.Direction, basket.Sign);
+ if (legs.Any(l => !_market.Has(l.Pair.Name, t)))
+ {
+ return false;
+ }
+
+ var moment = field == Field.Open ? _market.Clock[t] : _market.ClosesAt(t);
+ var level = basket.Levels.Count;
+ double index, pips;
+ var c = unit.Data.Position[t];
+ if (field == Field.Close && c >= 0)
+ {
+ var signal = unit.Signal(_engine, _rules, basket.Sign);
+ (index, pips) = (signal.Index[c], signal.Pips[c]);
+ }
+ else
+ {
+ var a = (double)Mid(unit.Data.Unit.A, t, field);
+ var b = unit.Data.Unit.B is { } legB ? (double)Mid(legB, t, field) : 0d;
+ (index, pips) = (unit.Data.Index(_rules.Signal, basket.Sign, a, b), unit.Data.PipIndex(basket.Sign, a, b));
+ }
+
+ basket.Levels.Add(new Level(index, pips));
+ foreach (var (pair, side) in legs)
+ {
+ var quote = Quote(pair, t, field);
+ var price = side == Direction.Buy ? quote.Ask : quote.Bid;
+ var exposure = order.Units * UsdPer(pair.Base, t, field);
+ var leverage = Leverage(pair);
+ var commission = exposure * _costs.Pair(pair.Name).CommissionPerSide;
+ var distance = _costs.StopDistance(pair.Name, side, price, leverage);
+ var position = new Position(basket, level, pair, side, order.Units, t, moment, price, exposure, _costs.Margin(exposure, leverage),
+ distance is { } d ? (side == Direction.Buy ? price - d : price + d) : null, field == Field.Close)
+ {
+ Commission = commission,
+ };
+ _cash -= commission;
+ _commission += commission;
+ _positions.Add(position);
+ basket.Positions.Add(position);
+ _fills.Add(new BacktestFill(_market.Day(t), pair.Name, side == Direction.Buy ? OrderSide.Buy : OrderSide.Sell, order.Units, price, exposure, commission, order.Reason));
+ }
+
+ basket.OpenedMoment ??= moment;
+ return true;
+ }
+
+ private void ClosePosition(Position position, int t, decimal price, DateTimeOffset at, Field field, string reason)
+ {
+ Finance(position, at);
+ var pair = position.Pair;
+ var sign = position.Side == Direction.Buy ? 1m : -1m;
+ var pnl = sign * position.Units * (price - position.EntryPrice) * UsdPer(pair.Quote, t, field);
+ var exposure = position.Units * UsdPer(pair.Base, t, field);
+ var commission = exposure * _costs.Pair(pair.Name).CommissionPerSide;
+ _cash += pnl - commission;
+ _commission += commission;
+ position.Commission += commission;
+ position.Open = false;
+ position.ExitBar = t;
+ position.ExitAt = at;
+ position.ExitPrice = price;
+ position.ExitReason = reason;
+ position.Result = pnl - position.Commission - position.Financing;
+ _positions.Remove(position);
+
+ // The closing fill carries the commission of the close and the financing of the whole life of the position.
+ _fills.Add(new BacktestFill(_market.Day(t), pair.Name, position.Side == Direction.Buy ? OrderSide.Sell : OrderSide.Buy, position.Units, price, exposure,
+ commission + position.Financing, reason));
+ }
+
+ private void CloseAll(int t, string reason, Field field)
+ {
+ var at = field == Field.Open ? _market.Clock[t] : _market.ClosesAt(t);
+ if (reason == BasketReasons.Liquidation)
+ {
+ _notes.Add(new BacktestNote(_market.Day(t), BasketEngine.AccountSymbol, reason));
+ }
+
+ foreach (var basket in _baskets.Where(b => !b.Finished).ToList())
+ {
+ if (reason == BasketReasons.Liquidation)
+ {
+ _events.Add(Event(t, basket.Unit.Data.Unit.Name, BasketEventKinds.Close, reason, basket.Direction));
+ }
+
+ basket.Exit = reason;
+ foreach (var position in basket.Positions.Where(p => p.Open).ToList())
+ {
+ var quote = _market.Has(position.Pair.Name, t) ? Quote(position.Pair, t, field) : Quote(position.Pair, LastBar(position.Pair.Name, t), Field.Close);
+ ClosePosition(position, t, Exit(position, quote), at, field, reason);
+ }
+
+ Done(basket);
+ }
+
+ _pending.Clear();
+ }
+
+ private void Done(Basket basket)
+ {
+ if (basket.Positions.Count == 0)
+ {
+ // Decided but never filled: it never existed.
+ _baskets.Remove(basket);
+ _pending.RemoveAll(p => p.Basket == basket);
+ return;
+ }
+
+ if (basket.Positions.All(p => !p.Open))
+ {
+ basket.Finished = true;
+ _pending.RemoveAll(p => p.Basket == basket);
+ }
+ }
+
+ /// Charges the financing of the rollovers crossed since the last charge, on the exposure at the entry.
+ private void Finance(Position position, DateTimeOffset at)
+ {
+ var nights = FinancingCalendar.Nights(position.FinancedTo, at);
+ if (nights > 0)
+ {
+ var charge = _costs.Financing(position.Pair.Name, position.Side, position.Exposure, nights);
+ _cash -= charge;
+ _financing += charge;
+ position.Financing += charge;
+ }
+
+ if (at > position.FinancedTo)
+ {
+ position.FinancedTo = at;
+ }
+ }
+
+ // ----- risk «come dal vivo» -----
+
+ ///
+ /// SPEC 9.2 on the marked equity at this close: the day is measured from the previous day's point, the week from the last
+ /// point seven days back, the fall from the highest equity since the start or the last restart. After a trip the user is
+ /// assumed to restart seven days later (ADR 0011).
+ ///
+ private void StepRisk(int t, decimal equity)
+ {
+ var at = _market.ClosesAt(t);
+ if (_risk.Tripped && _risk.TrippedAt is { } tripped && at >= tripped + BacktestRisk.AssumedRestart)
+ {
+ _risk = RiskMonitor.Restart(_risk, at);
+ _peak = null;
+ }
+
+ var dayBase = _equity.Count > 0 ? _equity[^1].Equity : _engine.InitialCapital;
+ var weekBase = _engine.InitialCapital;
+ for (var i = _equityAt.Count - 1; i >= 0; i--)
+ {
+ if (_equityAt[i] <= at - TimeSpan.FromDays(7))
+ {
+ weekBase = _equity[i].Equity;
+ break;
+ }
+ }
+
+ _peak = Math.Max(_peak ?? (_equity.Count == 0 ? _engine.InitialCapital : equity), equity);
+ _measures = new RiskMeasures(RiskMeasures.Change(equity, dayBase), RiskMeasures.Change(equity, weekBase), RiskMeasures.Change(equity, _peak.Value));
+ _risk = RiskMonitor.Step(_risk, _measures, at, RiskLimits.Default).State;
+ }
+
+ // ----- prices -----
+
+ ///
+ /// The quote of a pair at a field of bar t. With the source's ask: its bid and ask, widened around the mid by (m − 1) half
+ /// spreads at a cost multiplier m. Without: the reference price ± half the venue's spread (the pause spread inside the
+ /// daily pause on bars shorter than a day), the spread already multiplied.
+ ///
+ private BidAsk Quote(FxPair pair, int t, Field field)
+ {
+ var bid = (decimal)Value(_market.Bid(pair.Name), t, field);
+ if (_market.Ask(pair.Name) is { } askColumns)
+ {
+ var ask = (decimal)Value(askColumns, t, field);
+ var widen = _multiplier > 1m ? (_multiplier - 1m) * (ask - bid) / 2 : 0m;
+ return new BidAsk(bid - widen, ask + widen);
+ }
+
+ var moment = field == Field.Close ? _market.ClosesAt(t) : _market.Clock[t];
+ var half = _costs.Pair(pair.Name).SpreadPips(InPause(moment)) * pair.Pip / 2;
+ return new BidAsk(bid - half, bid + half);
+ }
+
+ private decimal Mid(FxPair pair, int t, Field field)
+ {
+ var bid = (decimal)Value(_market.Bid(pair.Name), t, field);
+ return _market.Ask(pair.Name) is { } ask ? (bid + (decimal)Value(ask, t, field)) / 2 : bid;
+ }
+
+ private static double Value(PriceColumns columns, int t, Field field) => field switch
+ {
+ Field.Open => columns.Open[t],
+ Field.High => columns.High[t],
+ Field.Low => columns.Low[t],
+ _ => columns.Close[t],
+ };
+
+ private static decimal Exit(Position position, BidAsk quote) => position.Side == Direction.Buy ? quote.Bid : quote.Ask;
+
+ private bool InPause(DateTimeOffset moment) => !_market.Daily && ServerClock.InDailyPause(moment);
+
+ ///
+ /// The dollars of one unit of a currency at a field of bar t, from the market's own pair with the dollar (its mid; the last
+ /// close when that pair has no bar there). Refused, in Italian, when the data has no such pair.
+ ///
+ private decimal UsdPer(string currency, int t, Field field)
+ {
+ if (currency == Currencies.Usd)
+ {
+ return 1m;
+ }
+
+ var pair = FxPairs.Of(currency, Currencies.Usd) ?? throw new ArgumentException($"{currency} non è una delle otto valute.", nameof(currency));
+ if (!_market.Has(pair.Name))
+ {
+ throw new InvalidOperationException($"Per convertire {currency} in dollari serve la coppia {pair.Name}, che non è nei dati.");
+ }
+
+ var bar = _market.Has(pair.Name, t) ? t : LastBar(pair.Name, t);
+ if (bar < 0)
+ {
+ throw new InvalidOperationException(string.Create(CultureInfo.InvariantCulture,
+ $"Per convertire {currency} in dollari serve un prezzo di {pair.Name} prima del {_market.Day(t):yyyy-MM-dd}, e non c'è."));
+ }
+
+ var mid = Mid(pair, bar, bar == t ? field : Field.Close);
+ return pair.Base == Currencies.Usd ? 1m / mid : mid;
+ }
+
+ /// The last bar at or before t where the symbol has a price, −1 when none.
+ private int LastBar(string symbol, int t)
+ {
+ if (!_lastBar.TryGetValue(symbol, out var last))
+ {
+ last = new int[_market.Count];
+ var known = -1;
+ for (var i = 0; i < last.Length; i++)
+ {
+ known = _market.Has(symbol, i) ? i : known;
+ last[i] = known;
+ }
+
+ _lastBar[symbol] = last;
+ }
+
+ return last[t];
+ }
+
+ /// The equity at the close of bar t (longs at the bid, shorts at the ask; at the mid when asked) and the margin committed.
+ private (decimal Equity, decimal Margin) Marks(int t, bool mid)
+ {
+ var equity = _cash;
+ foreach (var position in _positions)
+ {
+ equity += Unrealised(position, t, mid);
+ }
+
+ return (equity, Margin());
+ }
+
+ private decimal Unrealised(Position position, int t, bool mid)
+ {
+ var bar = _market.Has(position.Pair.Name, t) ? t : LastBar(position.Pair.Name, t);
+ var mark = mid ? Mid(position.Pair, bar, Field.Close) : Exit(position, Quote(position.Pair, bar, Field.Close));
+ var sign = position.Side == Direction.Buy ? 1m : -1m;
+ return sign * position.Units * (mark - position.EntryPrice) * UsdPer(position.Pair.Quote, t, Field.Close);
+ }
+
+ private decimal BasketValue(Basket basket, int t) => basket.Positions.Where(p => p.Open).Sum(p => Unrealised(p, t, mid: false));
+
+ private decimal Margin() => _positions.Sum(p => p.Margin);
+
+ // ----- signals -----
+
+ /// The sign of the unit's index at point c: fixed for one pair, chains and ratios; −sign(ρ) for a disjoint couple.
+ private int? Sign(Unit unit, int c) => unit.Data.Unit.FixedSign ?? Relations.Sign(RelationKind.Disjoint, unit.Data.Correlation(c, _rules.Window));
+
+ private double Z(UnitSignal signal, int c)
+ {
+ var at = c + _rules.SignalShift;
+ return at >= 0 && at < signal.Z.Length ? signal.Z[at] : double.NaN;
+ }
+
+ private static double? Finite(double? value) => value is { } v && double.IsFinite(v) ? v : null;
+
+ private static double Mean(List levels, Func value)
+ {
+ var sum = 0d;
+ foreach (var level in levels)
+ {
+ sum += value(level);
+ }
+
+ return sum / levels.Count;
+ }
+
+ /// The legs of a unit traded in a direction: leg A with the basket, leg B with it times the sign of the index.
+ private static List<(FxPair Pair, Direction Side)> Legs(Unit unit, int direction, int sign)
+ {
+ var legs = new List<(FxPair, Direction)> { (unit.Data.Unit.A, direction > 0 ? Direction.Buy : Direction.Sell) };
+ if (unit.Data.Unit.B is { } b)
+ {
+ legs.Add((b, direction * sign > 0 ? Direction.Buy : Direction.Sell));
+ }
+
+ return legs;
+ }
+
+ private BasketEvent Event(int t, string unit, string kind, string reason, int direction) =>
+ new(_market.ClosesAt(t), _market.Day(t), unit, kind, reason, direction);
+
+ // ----- the end -----
+
+ private BasketRunResult Finish()
+ {
+ var traces = new List();
+ var trades = new List();
+ var baskets = new List();
+ foreach (var basket in _baskets.Where(b => b.Positions.Count > 0).OrderBy(b => b.Id))
+ {
+ var open = !basket.Finished;
+ var positions = new List();
+ foreach (var p in basket.Positions)
+ {
+ if (p.Open && _last >= 0)
+ {
+ // Still open at the end: valued at the last marks, without a closing commission.
+ var bar = _market.Has(p.Pair.Name, _last) ? _last : LastBar(p.Pair.Name, _last);
+ var mark = Exit(p, Quote(p.Pair, bar, Field.Close));
+ var value = Unrealised(p, _last, mid: false);
+ positions.Add(new BasketPositionTrace(p.Level, p.Pair.Name, p.Side, p.Units, p.EntryBar, p.EntryAt, p.EntryPrice, null, null, mark,
+ BasketReasons.End, p.Commission, p.Financing, value - p.Commission - p.Financing));
+ }
+ else
+ {
+ positions.Add(new BasketPositionTrace(p.Level, p.Pair.Name, p.Side, p.Units, p.EntryBar, p.EntryAt, p.EntryPrice, p.ExitBar, p.ExitAt, p.ExitPrice,
+ p.ExitReason ?? BasketReasons.End, p.Commission, p.Financing, p.Result));
+ }
+ }
+
+ var reason = open ? BasketReasons.End : basket.Exit ?? BasketReasons.End;
+ var exitBar = open ? null : basket.Positions.Max(p => p.ExitBar);
+ var result = positions.Sum(p => p.Result);
+ var name = basket.Unit.Data.Unit.Name;
+ traces.Add(new BasketTrace(basket.Id, name, basket.Direction, basket.Sigma, positions, exitBar, reason));
+
+ // A trade per basket: Invested is the margin of all its positions at their entries, what the basket committed.
+ trades.Add(new BacktestTrade(name, _market.Day(basket.Positions[0].EntryBar), exitBar is { } closed ? _market.Day(closed) : null,
+ basket.Positions.Sum(p => p.Margin), result, positions.Sum(p => p.Commission + p.Financing)));
+ baskets.Add(new BacktestBasket(name, basket.OpenedMoment!.Value, open ? null : basket.Positions.Max(p => p.ExitAt), basket.FirstUnits,
+ basket.Levels.Count, [.. basket.Unit.Data.Unit.Legs.Select(l => l.Name)], reason, result));
+ }
+
+ var run = new BacktestRun("USD", _engine.InitialCapital, _equity, _fills, trades, [], _notes) { Baskets = baskets };
+ return new BasketRunResult(run, traces, _events, _commission, _financing);
+ }
+
+ // ----- state -----
+
+ private enum Field
+ {
+ Open,
+ High,
+ Low,
+ Close,
+ }
+
+ private enum PendingKind
+ {
+ Open,
+ Add,
+ Close,
+ }
+
+ private sealed record Pending(PendingKind Kind, Basket Basket, decimal Units, string Reason);
+
+ /// The levels decided on this close and not yet filled: the limits of the next candidates count them.
+ private sealed class Plan
+ {
+ public List Legs { get; } = [];
+
+ public decimal Margin { get; set; }
+ }
+
+ private sealed class Unit(int index, BasketUnit unit, UnitData data)
+ {
+ private readonly Dictionary _signals = [];
+
+ public int Index { get; } = index;
+
+ public BasketUnit Definition { get; } = unit;
+
+ public UnitData Data { get; } = data;
+
+ /// The refusal of the unit's last decision, so a spell of the same refusal is written once.
+ public string? Refused { get; set; }
+
+ public UnitSignal Signal(BasketEngine engine, BasketRules rules, int sign)
+ {
+ if (!_signals.TryGetValue(sign, out var signal))
+ {
+ var baseline = rules.MaxRvol is null ? (int?)null : rules.BaselineBars ?? BaselineBars(engine.Market);
+ signal = engine.Cached(
+ string.Create(CultureInfo.InvariantCulture, $"signal|{Definition.Name}|{rules.Signal}|{sign}|{rules.Window}|{baseline}|{rules.ShortBars}"),
+ () => new UnitSignal(Data, rules.Signal, sign, rules.Window, baseline, rules.ShortBars));
+ _signals[sign] = signal;
+ }
+
+ return signal;
+ }
+
+ /// Twenty market days of bars: 20 on daily bars, 20 × 96 on 15-minute bars.
+ private static int BaselineBars(BasketMarket market) =>
+ market.Daily ? BasketIndex.DefaultBaselineDays : BasketIndex.BaselineBars((int)(TimeSpan.FromDays(1) / market.Length));
+ }
+
+ private sealed class Basket(int id, Unit unit, int direction, int sign, double sigma, int decisionBar, int openedAt, decimal firstUnits)
+ {
+ public int Id { get; } = id;
+
+ public Unit Unit { get; } = unit;
+
+ public int Direction { get; } = direction;
+
+ public int Sign { get; } = sign;
+
+ /// σ of the index frozen at the decision that opened the basket.
+ public double Sigma { get; } = sigma;
+
+ public int DecisionBar { get; } = decisionBar;
+
+ /// The point of the unit's series where the basket was decided: its age in bars is counted from here.
+ public int OpenedAt { get; } = openedAt;
+
+ public decimal FirstUnits { get; } = firstUnits;
+
+ public DateTimeOffset? OpenedMoment { get; set; }
+
+ public List Levels { get; } = [];
+
+ public List Positions { get; } = [];
+
+ /// Why the basket is closing or closed; null while it runs.
+ public string? Exit { get; set; }
+
+ public bool Finished { get; set; }
+
+ public bool Waiting(List pending) => pending.Any(p => p.Basket == this);
+ }
+
+ /// One level: the index and the pip index at its fill.
+ private sealed record Level(double Index, double Pips);
+
+ private sealed class Position(
+ Basket basket, int level, FxPair pair, Direction side, decimal units, int entryBar, DateTimeOffset entryAt, decimal entryPrice,
+ decimal exposure, decimal margin, decimal? stop, bool atClose)
+ {
+ public Basket Basket { get; } = basket;
+
+ public int Level { get; } = level;
+
+ public FxPair Pair { get; } = pair;
+
+ public Direction Side { get; } = side;
+
+ public decimal Units { get; } = units;
+
+ public int EntryBar { get; } = entryBar;
+
+ public DateTimeOffset EntryAt { get; } = entryAt;
+
+ public decimal EntryPrice { get; } = entryPrice;
+
+ /// The USD exposure at the entry: margin and financing are computed on it.
+ public decimal Exposure { get; } = exposure;
+
+ public decimal Margin { get; } = margin;
+
+ /// The mandatory stop, when the venue imposes one.
+ public decimal? Stop { get; } = stop;
+
+ /// Filled at a close (the comparison configuration): no stop is checked inside that bar.
+ public bool AtClose { get; } = atClose;
+
+ public DateTimeOffset FinancedTo { get; set; } = entryAt;
+
+ public decimal Commission { get; set; }
+
+ public decimal Financing { get; set; }
+
+ public bool Open { get; set; } = true;
+
+ public int? ExitBar { get; set; }
+
+ public DateTimeOffset? ExitAt { get; set; }
+
+ public decimal? ExitPrice { get; set; }
+
+ public string? ExitReason { get; set; }
+
+ public decimal Result { get; set; }
+ }
+}
diff --git a/src/Anubis/Backtest/Trials.cs b/src/Anubis/Backtest/Trials.cs
index c313b1b..195256c 100644
--- a/src/Anubis/Backtest/Trials.cs
+++ b/src/Anubis/Backtest/Trials.cs
@@ -85,6 +85,15 @@ public sealed record TrialPlan(
///
public string? Judged { get; init; }
+ ///
+ /// The mode of a basket trial ( ): «come_dal_vivo», the only one a verdict comes from, or
+ /// «alla_lettera». Null for the daily families, so their plans and hashes stay as they were.
+ ///
+ public string? Mode { get; init; }
+
+ /// The venue's costs a basket trial runs with, with their date and source; null for the daily families.
+ public VenueCosts? Costs { get; init; }
+
public static readonly JsonSerializerOptions Json = new()
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
diff --git a/src/Anubis/Baskets/BasketIndex.cs b/src/Anubis/Baskets/BasketIndex.cs
index 34cfd92..37cbfa0 100644
--- a/src/Anubis/Baskets/BasketIndex.cs
+++ b/src/Anubis/Baskets/BasketIndex.cs
@@ -289,6 +289,78 @@ public static class BasketIndex
return baseline > 0 ? current / baseline : null;
}
+ ///
+ /// at every bar in one pass (Phase 14, as ADR 0028 asked): σ_short of every bar once, then the median of
+ /// the last of them from a window kept sorted, so each bar costs a binary search and a
+ /// shift instead of a sort. The same numbers as , bit for bit; not a number where it is null.
+ ///
+ public static double[] RollingRvol(IReadOnlyList index, int baselineBars = DefaultBaselineBars, int shortBars = DefaultShortBars)
+ {
+ ArgumentNullException.ThrowIfNull(index);
+ ArgumentOutOfRangeException.ThrowIfLessThan(baselineBars, 1);
+ ArgumentOutOfRangeException.ThrowIfLessThan(shortBars, 2);
+ var n = index.Count;
+ var rvol = new double[n];
+ Array.Fill(rvol, double.NaN);
+ var sigmas = new double[n];
+ for (var t = 0; t < n; t++)
+ {
+ sigmas[t] = ShortSigma(index, t, shortBars) ?? double.NaN;
+ }
+
+ // The window holds σ_short of bars t − baseline + 1 … t, sorted; a missing one makes the whole window unknown.
+ var window = new double[baselineBars];
+ var count = 0;
+ var missing = 0;
+ for (var t = 0; t < n; t++)
+ {
+ if (t >= baselineBars)
+ {
+ Remove(sigmas[t - baselineBars]);
+ }
+
+ Insert(sigmas[t]);
+ if (t + 1 < baselineBars || missing > 0)
+ {
+ continue;
+ }
+
+ var middle = baselineBars / 2;
+ var baseline = baselineBars % 2 == 1 ? window[middle] : (window[middle - 1] + window[middle]) / 2;
+ rvol[t] = baseline > 0 ? sigmas[t] / baseline : double.NaN;
+ }
+
+ return rvol;
+
+ void Insert(double value)
+ {
+ if (double.IsNaN(value))
+ {
+ missing++;
+ return;
+ }
+
+ var at = Array.BinarySearch(window, 0, count, value);
+ at = at < 0 ? ~at : at;
+ Array.Copy(window, at, window, at + 1, count - at);
+ window[at] = value;
+ count++;
+ }
+
+ void Remove(double value)
+ {
+ if (double.IsNaN(value))
+ {
+ missing--;
+ return;
+ }
+
+ var at = Array.BinarySearch(window, 0, count, value);
+ Array.Copy(window, at + 1, window, at, count - at - 1);
+ count--;
+ }
+ }
+
/// The volatility filter: a new entry only with a known Rvol no higher than .
public static bool AllowsEntry(double? rvol, double max = DefaultMaxRvol) => rvol is { } r && r <= max;
diff --git a/src/Anubis/Trading/ReasonCatalog.cs b/src/Anubis/Trading/ReasonCatalog.cs
index 6c9cd76..2311f04 100644
--- a/src/Anubis/Trading/ReasonCatalog.cs
+++ b/src/Anubis/Trading/ReasonCatalog.cs
@@ -102,6 +102,28 @@ public static class ReasonCatalog
["restart"] = "Annullato alla ripartenza del bot: se era ancora dovuto, è stato riproposto.",
["protected_restart"] = "Deciso prima del ripristino: non parte, potrebbe essere già partito allora.",
["recovered"] = "Recuperato dopo un'assenza.",
+ // Baskets (Phase 14): exits.
+ ["target"] = "Obiettivo raggiunto: il paniere si chiude tutto.",
+ ["stop_basket"] = "Stop del paniere (profilo Prudente, o stop in obiettivi del confronto con la replica): il paniere si chiude.",
+ ["account_stop"] = "Perdita aperta pari o oltre il 9% del saldo: si chiude tutto e niente ingressi fino al cambio di giorno del server.",
+ ["mandatory_stop"] = "Stop obbligatorio della piattaforma raggiunto: la posizione è chiusa.",
+ ["orphan_leg"] = "Lo stop obbligatorio ha chiuso una gamba del paniere: l'altra, rimasta sola, si chiude all'esecuzione successiva.",
+ ["liquidation"] = "Patrimonio sotto metà del margine iniziale delle posizioni aperte: la piattaforma chiude tutto.",
+ ["end"] = "Ancora aperto alla fine dei dati: valutato agli ultimi prezzi.",
+ // Baskets (Phase 14): refusals and notes.
+ ["gate_open_loss"] = "Perdita aperta pari o oltre il 2% del saldo: niente nuovi panieri, le mediazioni continuano.",
+ ["paused_until_next_day"] = "Dopo lo stop sul conto niente ingressi fino al cambio di giorno del server, alle 17 di New York.",
+ ["half_size"] = "Limiti di rischio: il livello parte a metà, o a un quarto, della misura.",
+ ["below_venue_minimum"] = "Livello sotto il minimo della piattaforma, 1.000 dollari per posizione: non parte.",
+ ["margin_limit"] = "Margine impegnato oltre il 40% del patrimonio: niente nuovi livelli.",
+ ["max_positions"] = "Raggiunto il numero massimo di posizioni aperte, 9 sul conto Demo condiviso: niente nuovi livelli.",
+ ["opposite_position"] = "C'è già una posizione opposta sullo stesso strumento: ingresso scartato.",
+ ["currency_exposure"] = "Esposizione netta su una valuta oltre due ingressi.",
+ ["cost_rule"] = "Obiettivo sotto tre volte il costo di andata e ritorno del paniere.",
+ ["rvol_filter"] = "Volatilità recente oltre il doppio del solito, o non ancora nota: niente nuovi panieri.",
+ ["correlation_low"] = "Correlazione tra le due gambe troppo bassa sul segno atteso: niente paniere.",
+ ["max_open_baskets"] = "Già aperti tutti i panieri ammessi insieme.",
+ ["clock_window"] = "Fuori dall'orario degli ingressi: fine settimana, pausa giornaliera o fascia oraria.",
};
public static string Text(string code) => Texts.TryGetValue(code, out var text) ? text : code;
diff --git a/tests/Anubis.Tests/BasketEngineTests.cs b/tests/Anubis.Tests/BasketEngineTests.cs
new file mode 100644
index 0000000..e87c9d1
--- /dev/null
+++ b/tests/Anubis.Tests/BasketEngineTests.cs
@@ -0,0 +1,452 @@
+using Anubis.Backtest;
+using Anubis.Baskets;
+using Anubis.Data;
+
+namespace Anubis.Tests;
+
+///
+/// The basket engine of Phase 14 (issue #127): a margin account with independent positions, bought at the ask and sold at the
+/// bid, the venue's mandatory stop, liquidation, financing, the document's account rules (9% stop, 2% gate) and, «come dal
+/// vivo», the limits of SPEC 9.2 and of the plan's margin table. Every money figure is computed by hand in the comment next
+/// to it; the comparison configuration is checked against the stylised replica of appendix G.
+///
+[TestClass]
+public sealed class BasketEngineTests
+{
+ private static readonly FxPair EurUsd = FxPairs.Get("EURUSD");
+ private static readonly FxPair UsdChf = FxPairs.Get("USDCHF");
+ private static readonly FxPair UsdJpy = FxPairs.Get("USDJPY");
+ private static readonly FxPair GbpUsd = FxPairs.Get("GBPUSD");
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public void AToyTwoLegBasketGivesTheResultComputedByHand()
+ {
+ // Tuesday 10 March 2026 from 10:00 UTC (06:00 in New York): no pause, no weekend, no rollover (21:00 UTC).
+ // EURUSD bid/ask one pip wide, USDCHF two pips. Bars 0–9 alternate, so the chain index X = E/pip + C/pip alternates
+ // 19,000 / 19,004; bar 10 drops to 18,985: z = −2.67 over 10 bars, the spread is bought (both legs long, chain s = +1).
+ var first = new DateTimeOffset(2026, 3, 10, 10, 0, 0, TimeSpan.Zero);
+ decimal[] e = [.. Alt(1.1000m, 1.1002m, 10), 1.0990m, 1.0990m, 1.0997m, 1.0998m, 1.1000m];
+ decimal[] c = [.. Alt(0.8000m, 0.8002m, 10), 0.7995m, 0.7995m, 0.8000m, 0.8001m, 0.8003m];
+ var data = BasketSynthetic.Quarters(first, new Dictionary
+ {
+ ["EURUSD"] = [.. e.Select(m => BasketSynthetic.Mid(m, 0.0001m))],
+ ["USDCHF"] = [.. c.Select(m => BasketSynthetic.Mid(m, 0.0002m))],
+ });
+ var rules = new BasketRules([BasketUnit.Of(EurUsd, UsdChf)])
+ {
+ Window = 10,
+ Target = 10m,
+ Distance = 1_000m,
+ LotPer10k = 0.1m,
+ Mode = BasketMode.AsDocument,
+ MaxRvol = null,
+ MinCorrelation = null,
+ };
+
+ var result = Run(data, rules, VenueCosts.Etoro, 100_000m);
+
+ // Units: 0.1 × 100,000 / 10,000 × 100,000 = 100,000 on each leg (EUR 1.0990 and USD 1 both above 1,000 USD).
+ // Filled at bar 11's open: EURUSD bought at the ask 1.09905, USDCHF at the ask 0.7996.
+ // Bar 12 close: pips (1.09965 − 1.09905) + (0.7999 − 0.7996) = 6 + 3 = 9 < 10; bar 13: 7 + 4 = 11 ≥ 10: target.
+ // Sold at bar 14's open at the bid: EURUSD 1.09995, USDCHF 0.8002.
+ // EURUSD: 100,000 × 0.0009 = 90.00 USD. USDCHF: 100,000 × 0.0006 = 60 CHF ÷ 0.8003 (the mid at the exit) = 74.9719 USD.
+ // Commission 0.005% a side on the USD exposure at the mid: opening 109,900 → 5.495 and 100,000 → 5.00; closing
+ // 110,000 → 5.50 and 100,000 → 5.00; together 20.995. No rollover crossed: no financing.
+ // Result: 90 + 74.97188554 − 20.995 = 143.97688554 → 143.98 USD.
+ var basket = result.Run.Baskets.Single();
+ Assert.AreEqual(BasketReasons.Target, basket.ExitReason);
+ Assert.AreEqual(1, basket.Levels);
+ Assert.AreEqual(100_000m, basket.Units);
+ Assert.AreEqual(143.98m, Math.Round(basket.Result, 2));
+ Assert.AreEqual(143.98m, Math.Round(result.Run.NetResult, 2));
+ Assert.AreEqual(20.995m, result.Commission);
+ Assert.AreEqual(0m, result.Financing);
+ Assert.AreEqual(20.995m, result.Run.Fees);
+
+ var fills = result.Run.Fills;
+ Assert.AreEqual(4, fills.Count);
+ Assert.AreEqual(1.09905m, fills.Single(f => f.Symbol == "EURUSD" && f.Side == Trading.OrderSide.Buy).Price);
+ Assert.AreEqual(0.7996m, fills.Single(f => f.Symbol == "USDCHF" && f.Side == Trading.OrderSide.Buy).Price);
+ Assert.AreEqual(1.09995m, fills.Single(f => f.Symbol == "EURUSD" && f.Side == Trading.OrderSide.Sell).Price);
+ Assert.AreEqual(0.8002m, fills.Single(f => f.Symbol == "USDCHF" && f.Side == Trading.OrderSide.Sell).Price);
+
+ var trace = result.Traces.Single();
+ Assert.AreEqual(11, trace.Positions[0].EntryBar);
+ Assert.AreEqual(14, trace.Positions[0].ExitBar);
+ Assert.AreEqual(143.98m, Math.Round(trace.Positions.Sum(p => p.Result), 2));
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public void TheAccountStopFiresAtTheExactThresholdAndResumesAtTheServerDayChange()
+ {
+ // Tuesday 13 January 2026 from 13:00 UTC (08:00 New York); the server day changes at 17:00 New York, 22:00 UTC.
+ // 100,000 EURUSD bought at exactly 1.0000 on bar 11 (no spread, no cost): balance 10,000.
+ // Bar 11 closes at 0.99101: open loss 899 / 10,000 = 8.99%, nothing. Bar 12 closes at 0.9910: 9.00%, the stop fires.
+ var first = new DateTimeOffset(2026, 1, 13, 13, 0, 0, TimeSpan.Zero);
+ var rows = new List<(QuoteSide, QuoteSide)>();
+ rows.AddRange(Alt(1.0000m, 1.0001m, 10).Select(p => BasketSynthetic.Mid(p, 0m)));
+ rows.Add(BasketSynthetic.Mid(0.9990m, 0m));
+ rows.Add(Same(new QuoteSide(1.0000m, 1.0000m, 0.99101m, 0.99101m)));
+ rows.Add(Same(new QuoteSide(0.99101m, 0.99101m, 0.9910m, 0.9910m)));
+ rows.AddRange(Alt(0.9910m, 0.9911m, 12).Select(p => BasketSynthetic.Mid(p, 0m))); // bars 13–24
+ rows.Add(BasketSynthetic.Mid(0.9890m, 0m)); // bar 25, 19:15 UTC: a signal
+ rows.AddRange(Alt(0.9890m, 0.9891m, 10).Select(p => BasketSynthetic.Mid(p, 0m))); // bars 26–35
+ rows.Add(BasketSynthetic.Mid(0.9870m, 0m)); // bar 36, 22:00 UTC: a signal
+ rows.Add(BasketSynthetic.Mid(0.9870m, 0m));
+ var data = BasketSynthetic.Quarters(first, new Dictionary { ["EURUSD"] = [.. rows] });
+ var rules = SingleRules(EurUsd, BasketMode.AsDocument) with { LotPer10k = 1m, ClockWindows = false };
+
+ var result = Run(data, rules, VenueCosts.None);
+
+ var stops = result.Events.Where(x => x.Reason == BasketReasons.AccountStop).ToList();
+ Assert.AreEqual(1, stops.Count, "8.99% does not fire, 9.00% does");
+ var trigger = first.AddMinutes(15 * 13);
+ Assert.AreEqual(trigger, stops[0].At, "at the close of bar 12");
+ Assert.AreEqual(BasketReasons.AccountStop, result.Run.Baskets[0].ExitReason);
+ Assert.AreEqual(-900m, result.Run.Baskets[0].Result);
+
+ var resume = ServerClock.NextDayStart(trigger);
+ Assert.AreEqual(new DateTimeOffset(2026, 1, 13, 22, 0, 0, TimeSpan.Zero), resume);
+ var paused = result.Events.Single(x => x.Reason == BasketReasons.PausedUntilNextDay);
+ Assert.AreEqual(first.AddMinutes(15 * 26), paused.At, "the signal of bar 25 is refused");
+ Assert.IsFalse(result.Events.Any(x => x.Kind is BasketEventKinds.Open or BasketEventKinds.Add && x.At > trigger && x.At <= resume));
+ var reopened = result.Events.Where(x => x.Kind == BasketEventKinds.Open && x.At > trigger).ToList();
+ Assert.AreEqual(1, reopened.Count);
+ Assert.AreEqual(resume.AddMinutes(15), reopened[0].At, "the first bar of the next server day opens");
+
+ // During the daily pause the stop reads mid prices: a bid of 0.9900 and an ask of 1.0100 around a mid of 1.0000 would
+ // be a 10% loss at the bid, but the mid has not moved. The same quote outside the pause fires the stop.
+ Assert.AreEqual(0, PauseRun(wideAt: 16).Events.Count(x => x.Reason == BasketReasons.AccountStop), "bar 16 closes at 17:15 New York: in the pause");
+ Assert.AreEqual(1, PauseRun(wideAt: 12).Events.Count(x => x.Reason == BasketReasons.AccountStop), "bar 12 closes at 16:15 New York: outside");
+
+ static BasketRunResult PauseRun(int wideAt)
+ {
+ var start = new DateTimeOffset(2026, 1, 13, 18, 0, 0, TimeSpan.Zero);
+ var quotes = new List<(QuoteSide, QuoteSide)>();
+ quotes.AddRange(Alt(1.0000m, 1.0001m, 10).Select(p => BasketSynthetic.Mid(p, 0m)));
+ quotes.Add(BasketSynthetic.Mid(0.9990m, 0m));
+ for (var t = 11; t < 20; t++)
+ {
+ quotes.Add(t == wideAt ? BasketSynthetic.Mid(1.0000m, 0.0200m) : BasketSynthetic.Mid(1.0000m, 0m));
+ }
+
+ var pauseData = BasketSynthetic.Quarters(start, new Dictionary { ["EURUSD"] = [.. quotes] });
+ return Run(pauseData, SingleRules(EurUsd, BasketMode.AsDocument) with { LotPer10k = 1m }, VenueCosts.None);
+ }
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public void TheTwoPercentGateStopsNewBasketsButLetsAveragingThrough()
+ {
+ // 15,000 EURUSD bought at 0.9985; bar 12 closes at 0.9840: open loss 217.50 / 10,000 = 2.175%. The averaging rule
+ // holds (−145 pips ≤ −15, z still ≤ −2) and goes through; USDJPY's signal on the same bar is refused by the gate.
+ var result = Run(GateData(), GateRules(BasketMode.AsDocument), VenueCosts.None);
+
+ var eur = result.Traces.Single(x => x.Unit == "EURUSD");
+ Assert.AreEqual(2, eur.Levels);
+ Assert.AreEqual(13, eur.Positions[1].EntryBar);
+ Assert.IsFalse(result.Traces.Any(x => x.Unit == "USDJPY"));
+ var refused = result.Events.Single(x => x.Unit == "USDJPY" && x.Kind == BasketEventKinds.Refused);
+ Assert.AreEqual(BasketReasons.GateOpenLoss, refused.Reason);
+ Assert.AreEqual(1, result.Run.Notes.Count(n => n.Reason == BasketReasons.GateOpenLoss));
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public void AsLiveADayAtMinusTwoPercentStopsAveragingToo()
+ {
+ // The same days «come dal vivo»: the equity falls from 10,000 to 9,782.50 in one day (−2.175%), so SPEC 9.2 blocks new
+ // baskets and averaging for 24 hours.
+ var result = Run(GateData(), GateRules(BasketMode.AsLive), VenueCosts.None);
+
+ var eur = result.Traces.Single(x => x.Unit == "EURUSD");
+ Assert.AreEqual(1, eur.Levels);
+ Assert.AreEqual(BasketReasons.DailyLossBlock, result.Events.Single(x => x.Unit == "EURUSD" && x.Kind == BasketEventKinds.Refused).Reason);
+ Assert.AreEqual(BasketReasons.DailyLossBlock, result.Events.Single(x => x.Unit == "USDJPY" && x.Kind == BasketEventKinds.Refused).Reason);
+ Assert.IsFalse(result.Traces.Any(x => x.Unit == "USDJPY"));
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public void AsLiveHalfSizeAndQuarterSizeFollowSpec92()
+ {
+ // 10,000 EURUSD bought at 0.9985 fall 6% in a day: the Prudente basket stop closes them (5.99% of equity, over 1%).
+ // The week is −5.99%: SPEC 9.2 halves the size for seven days, so GBPUSD three days later opens 5,000 units, not 10,000.
+ var half = Run(SizeData(0.06), SizeRules(), VenueCosts.None);
+ var gbp = half.Traces.Single(x => x.Unit == "GBPUSD");
+ Assert.AreEqual(5_000m, gbp.Positions[0].Units);
+ Assert.AreEqual(BasketReasons.StopBasket, half.Run.Baskets[0].ExitReason);
+ Assert.AreEqual(1, half.Run.Notes.Count(n => n.Reason == BasketReasons.HalfSize));
+
+ // An 11% fall: the 9% account stop closes everything; the week is −10.98% and so is the fall from the high: both halve,
+ // a quarter together. 2,500 units.
+ var quarter = Run(SizeData(0.11), SizeRules(), VenueCosts.None);
+ Assert.AreEqual(BasketReasons.AccountStop, quarter.Run.Baskets[0].ExitReason);
+ Assert.AreEqual(2_500m, quarter.Traces.Single(x => x.Unit == "GBPUSD").Positions[0].Units);
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public void AsLiveALevelBelowTheVenueMinimumDoesNotStart()
+ {
+ // With 1,000 USD of capital the lot gives 1,000 units (EURUSD raised to 1,002 to reach 1,000 USD). After the 6% fall
+ // the GBPUSD level would be 500 units, 649.25 USD: under the venue minimum of 1,000 USD, so it does not start.
+ var result = Run(SizeData(0.06), SizeRules(), VenueCosts.None, 1_000m);
+ Assert.AreEqual(1_002m, result.Traces.Single(x => x.Unit == "EURUSD").Positions[0].Units);
+ Assert.IsFalse(result.Traces.Any(x => x.Unit == "GBPUSD"));
+ Assert.AreEqual(BasketReasons.BelowVenueMinimum, result.Events.Single(x => x.Unit == "GBPUSD" && x.Kind == BasketEventKinds.Refused).Reason);
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public void AsLiveTheMarginLimitAndThePositionLimitRefuseEntries()
+ {
+ // Ten pairs signal on the same bar. With 0.01 lots every level is small: nine open, the tenth would be the tenth
+ // position of the shared Demo and is refused.
+ var data = TenPairs();
+ var small = Run(data, TenRules(0.01m), VenueCosts.None);
+ Assert.AreEqual(9, small.Events.Count(x => x.Kind == BasketEventKinds.Open));
+ Assert.AreEqual(BasketReasons.PositionLimit, small.Events.Single(x => x.Kind == BasketEventKinds.Refused).Reason);
+
+ // With 0.05 lots the margin committed reaches 40% of the equity first: the levels after it are refused.
+ var large = Run(data, TenRules(0.05m), VenueCosts.None);
+ var opened = large.Events.Count(x => x.Kind == BasketEventKinds.Open);
+ Assert.IsTrue(opened is > 0 and < 9, $"{opened} opened");
+ Assert.IsTrue(large.Events.Where(x => x.Kind == BasketEventKinds.Refused).All(x => x.Reason == BasketReasons.MarginLimit));
+ Assert.AreEqual(10 - opened, large.Events.Count(x => x.Reason == BasketReasons.MarginLimit));
+ var margin = large.Run.Equity.Max(p => p.Invested);
+ Assert.IsTrue(margin <= 0.40m * 10_000m, $"margin {margin}");
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public void AsLiveNoOppositePositionOnTheSameInstrument()
+ {
+ // The chain EURUSD + USDCHF is bought on bar 10 (long EURUSD). On bar 12 EURUSD alone signals a sale: «come dal vivo»
+ // it would face the long EURUSD of the chain and is refused; «alla lettera» it opens.
+ double[] e = [.. BasketSynthetic.Alternate(1.1000, 1.1002, 10), 1.1000, 1.1000, .. Enumerable.Repeat(1.1040, 8)];
+ double[] c = [.. BasketSynthetic.Alternate(0.8000, 0.8002, 10), .. Enumerable.Repeat(0.7960, 10)];
+ var data = BasketSynthetic.Daily(new Dictionary { ["EURUSD"] = e, ["USDCHF"] = c });
+ var rules = new BasketRules([BasketUnit.Of(EurUsd, UsdChf), BasketUnit.OnePair(EurUsd)])
+ {
+ Window = 10,
+ Target = 1_000m,
+ Distance = 1_000m,
+ MaxOpenBaskets = 5,
+ MaxRvol = null,
+ MinCorrelation = null,
+ };
+
+ var live = Run(data, rules with { Mode = BasketMode.AsLive }, VenueCosts.None);
+ var refused = live.Events.Single(x => x.Unit == "EURUSD" && x.Kind == BasketEventKinds.Refused);
+ Assert.AreEqual(BasketReasons.OppositePosition, refused.Reason);
+ Assert.AreEqual(1, live.Traces.Count);
+
+ var letter = Run(data, rules with { Mode = BasketMode.AsDocument }, VenueCosts.None);
+ Assert.AreEqual(2, letter.Traces.Count);
+ Assert.AreEqual(-1, letter.Traces.Single(x => x.Unit == "EURUSD").Direction);
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public void LiquidationClosesEverythingBelowHalfTheMargin()
+ {
+ // 1,000 USD of capital, 9,000 EURUSD bought at the ask 0.998505: exposure 8,986.50 at the mid, margin at leverage 5
+ // 1,797.30, half of it 898.65. A fall of 1.5% in a day leaves about 862 of equity: below half the margin, every
+ // position closes at that close. A fall of 1.0% leaves about 906.5 (balance 999.55 less four nights of financing,
+ // 2.91, less 90.09 at the bid): no liquidation, but the 9% account stop (90.09 / 996.64 = 9.04%).
+ var deep = Run(LiquidationData(0.9835), SingleRules(EurUsd, BasketMode.AsDocument) with { LotPer10k = 0.9m }, VenueCosts.Etoro, 1_000m);
+ Assert.AreEqual(BasketReasons.Liquidation, deep.Run.Baskets.Single().ExitReason);
+ Assert.AreEqual(12, deep.Traces.Single().Positions.Single().ExitBar);
+ Assert.AreEqual(0.983495m, deep.Traces.Single().Positions.Single().ExitPrice, "the bid of that close");
+ Assert.AreEqual(1, deep.Run.Notes.Count(n => n.Reason == BasketReasons.Liquidation));
+
+ var shallow = Run(LiquidationData(0.9885), SingleRules(EurUsd, BasketMode.AsDocument) with { LotPer10k = 0.9m }, VenueCosts.Etoro, 1_000m);
+ Assert.AreEqual(BasketReasons.AccountStop, shallow.Run.Baskets.Single().ExitReason);
+ Assert.AreEqual(0, shallow.Run.Notes.Count(n => n.Reason == BasketReasons.Liquidation));
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Golden)]
+ public void TheEngineInItsComparisonSettingMatchesTheReplicaOnTwoHundredSeries()
+ {
+ // 200 seeded series: AR(1) with half-lives 20–100, driftless and drifting walks, 600–1,500 bars, prices exp(s) on
+ // EURUSD. Three cases of table G.4 (no stop, a stop of 90, a stop of 30 with growth): the engine, deciding and filling
+ // on the same close with no cost and no account rule, must make the replica's baskets, and its result in targets
+ // computed from the fill prices must be the replica's total.
+ var cases = new[] { ReplicaSettings.DocumentCases[0], ReplicaSettings.DocumentCases[4], ReplicaSettings.DocumentCases[14] };
+ // The series are independent: they run in parallel, each with its own assertions.
+ var baskets = 0;
+ Parallel.For(0, 200, i =>
+ {
+ var bars = 600 + (i * 900 / 199);
+ var s = (i % 4) switch
+ {
+ 0 or 1 => BasketSynthetic.Reverting(bars, Synthetic.Phi(20 + (i % 5 * 20)), 1_000 + i, 0.005),
+ 2 => BasketSynthetic.Walk(bars, 1_000 + i, 0, 0.005),
+ _ => BasketSynthetic.Walk(bars, 1_000 + i, i % 8 == 3 ? 0.0005 : -0.0005, 0.005),
+ };
+ var data = BasketSynthetic.Daily(new Dictionary { ["EURUSD"] = [.. s.Select(x => 1.1 * Math.Exp(x))] });
+ var logs = data.Bars("EURUSD").Close.Select(x => Math.Log(x)).ToArray();
+ var market = BasketMarket.Of(data);
+ foreach (var c in cases)
+ {
+ var replica = StylisedReplica.Run(logs, c.Settings);
+ var engine = new BasketEngine(market, VenueCosts.None, 10_000m).Run(BasketRules.Comparison(EurUsd, c.Settings));
+ Assert.AreEqual(replica.Baskets, engine.Traces.Count, $"series {i}, {c.Label} {c.StopLabel}: baskets");
+ var total = 0d;
+ for (var k = 0; k < replica.List.Count; k++)
+ {
+ var r = replica.List[k];
+ var x = engine.Traces[k];
+ var where = $"series {i}, {c.Label} {c.StopLabel}, basket {k}";
+ Assert.AreEqual(r.Direction, x.Direction, where);
+ CollectionAssert.AreEqual(r.EntryBars.ToArray(), x.Positions.Select(p => p.EntryBar).ToArray(), where);
+ Assert.AreEqual(r.ClosedAt, x.ExitBar, where);
+ Assert.AreEqual(r.Exit switch { ReplicaExits.Target => BasketReasons.Target, ReplicaExits.Stop => BasketReasons.StopBasket, _ => BasketReasons.End }, x.ExitReason, where);
+
+ // One target is k_T × σ of ln(price); the engine's σ is that of 10,000 · ln(price).
+ var target = c.Settings.TargetSigma * x.Sigma / 10_000;
+ total += x.Positions.Sum(p => x.Direction * (Math.Log((double)p.ExitPrice!.Value) - Math.Log((double)p.EntryPrice)) / target);
+ }
+
+ Assert.AreEqual(replica.Total, total, 1e-9, $"series {i}, {c.Label} {c.StopLabel}: total");
+ Interlocked.Add(ref baskets, replica.Baskets);
+ }
+ });
+
+ Assert.IsTrue(baskets > 5_000, $"{baskets} baskets compared");
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public void FiveNightsAreChargedFromTuesdayToFridayInTheEngine()
+ {
+ // Monday 19 January 2026 EURUSD fixes at 1.0985 against a window around 1.1001: z ≤ −2, buy. Filled on Tuesday's
+ // fixing (00:00 UTC) at the ask 1.098505; Thursday's fixing 1.1000 gives 14.9 pips ≥ 10: sold on Friday's (00:00 UTC).
+ // Rollovers crossed: Tuesday's (1), Wednesday's (3), Thursday's (1): five nights at the buy rate of 8.096 USD per
+ // 100,000. Exposure at Tuesday's mid: 1,000 × 1.0985 = 1,098.50 USD; financing 1,098.50 / 100,000 × 8.096 × 5 = 0.4446728.
+ double[] e = [.. BasketSynthetic.Alternate(1.1000, 1.1002, 10), 1.0985, 1.0985, 1.0985, .. Enumerable.Repeat(1.1000, 7)];
+ var data = BasketSynthetic.Daily(new Dictionary { ["EURUSD"] = e });
+ var result = Run(data, SingleRules(EurUsd, BasketMode.AsDocument), VenueCosts.Etoro);
+
+ var position = result.Traces.Single().Positions.Single();
+ Assert.AreEqual(BasketSynthetic.Midnight(new DateOnly(2026, 1, 20)), position.EntryAt);
+ Assert.AreEqual(BasketSynthetic.Midnight(new DateOnly(2026, 1, 23)), position.ExitAt);
+ Assert.AreEqual(1_098.5m / 100_000m * 8.096m * 5, position.Financing);
+ Assert.AreEqual(0.4446728m, result.Financing);
+ Assert.AreEqual(VenueCosts.Etoro.Financing("EURUSD", Direction.Buy, 1_098.5m, 5), result.Financing);
+ }
+
+ [TestMethod]
+ [TestCategory(Category.Unit)]
+ public void TheRollingRvolEqualsTheReference()
+ {
+ foreach (var (baseline, shortBars) in new[] { (20, 16), (50, 8) })
+ {
+ var x = BasketSynthetic.Walk(400, baseline, 0, 0.3);
+ var rolling = BasketIndex.RollingRvol(x, baseline, shortBars);
+ for (var t = 0; t < x.Length; t++)
+ {
+ var reference = BasketIndex.Rvol(x, t, baseline, shortBars);
+ Assert.AreEqual(reference ?? double.NaN, rolling[t], $"t {t}");
+ }
+ }
+ }
+
+ // ----- data of the tests -----
+
+ private static BasketRunResult Run(BarDataset data, BasketRules rules, VenueCosts costs, decimal capital = 10_000m) =>
+ new BasketEngine(BasketMarket.Of(data), costs, capital).Run(rules);
+
+ /// A single symbol of generation B on a 10-bar window: 10 pips of target, averaging too far to happen.
+ private static BasketRules SingleRules(FxPair pair, BasketMode mode) => new([BasketUnit.OnePair(pair)])
+ {
+ Window = 10,
+ Target = 10m,
+ Distance = 1_000m,
+ Mode = mode,
+ MaxRvol = null,
+ };
+
+ private static BarDataset GateData()
+ {
+ double[] e = [.. BasketSynthetic.Alternate(1.0000, 1.0002, 10), 0.9985, 0.9985, .. Enumerable.Repeat(0.9840, 8)];
+ double[] j = [.. BasketSynthetic.Alternate(150.00, 150.02, 12), .. Enumerable.Repeat(149.80, 8)];
+ return BasketSynthetic.Daily(new Dictionary { ["EURUSD"] = e, ["USDJPY"] = j });
+ }
+
+ private static BasketRules GateRules(BasketMode mode) => new([BasketUnit.OnePair(EurUsd), BasketUnit.OnePair(UsdJpy)])
+ {
+ Window = 10,
+ Target = 10m,
+ Distance = 15m,
+ LotPer10k = 0.15m,
+ Mode = mode,
+ MaxRvol = null,
+ };
+
+ private static BarDataset SizeData(double gap)
+ {
+ var low = 0.9985 * (1 - gap);
+ double[] e = [.. BasketSynthetic.Alternate(1.0000, 1.0002, 10), 0.9985, 0.9985, .. Enumerable.Repeat(low, 18)];
+ double[] g = [.. BasketSynthetic.Alternate(1.3000, 1.3002, 15), .. Enumerable.Repeat(1.2985, 15)];
+ return BasketSynthetic.Daily(new Dictionary { ["EURUSD"] = e, ["GBPUSD"] = g });
+ }
+
+ private static BasketRules SizeRules() => new([BasketUnit.OnePair(EurUsd), BasketUnit.OnePair(GbpUsd)])
+ {
+ Window = 10,
+ Target = 10m,
+ Distance = 1_000m,
+ LotPer10k = 0.1m,
+ Mode = BasketMode.AsLive,
+ Profile = BasketProfiles.Prudente,
+ MaxRvol = null,
+ };
+
+ private static BarDataset TenPairs()
+ {
+ var levels = new Dictionary(StringComparer.Ordinal)
+ {
+ ["EURUSD"] = 1.10,
+ ["GBPUSD"] = 1.30,
+ ["AUDUSD"] = 0.66,
+ ["NZDUSD"] = 0.60,
+ ["USDCAD"] = 1.40,
+ ["USDCHF"] = 0.85,
+ ["USDJPY"] = 150,
+ ["EURGBP"] = 0.846,
+ ["EURJPY"] = 165,
+ ["GBPJPY"] = 195,
+ };
+ return BasketSynthetic.Daily(levels.ToDictionary(
+ l => l.Key,
+ l => (double[])[.. BasketSynthetic.Alternate(l.Value, l.Value * 1.0002, 10), .. Enumerable.Repeat(l.Value * 0.9985, 10)],
+ StringComparer.Ordinal));
+ }
+
+ private static BasketRules TenRules(decimal lot) => new([.. TenPairs().Symbols.Select(s => BasketUnit.OnePair(FxPairs.Get(s)))])
+ {
+ Window = 10,
+ Target = 1_000m,
+ Distance = 1_000m,
+ LotPer10k = lot,
+ MaxOpenBaskets = 20,
+ Mode = BasketMode.AsLive,
+ MaxRvol = null,
+ };
+
+ private static BarDataset LiquidationData(double fall)
+ {
+ double[] e = [.. BasketSynthetic.Alternate(1.0000, 1.0002, 10), 0.9985, 0.9985, .. Enumerable.Repeat(fall, 8)];
+ return BasketSynthetic.Daily(new Dictionary { ["EURUSD"] = e });
+ }
+
+ private static IEnumerable Alt(decimal low, decimal high, int count) => Enumerable.Range(0, count).Select(i => i % 2 == 0 ? low : high);
+
+ private static (QuoteSide, QuoteSide) Same(QuoteSide side) => (side, side);
+}
diff --git a/tests/Anubis.Tests/BasketSynthetic.cs b/tests/Anubis.Tests/BasketSynthetic.cs
new file mode 100644
index 0000000..0128035
--- /dev/null
+++ b/tests/Anubis.Tests/BasketSynthetic.cs
@@ -0,0 +1,138 @@
+using Anubis.Backtest;
+using Anubis.Baskets;
+using Anubis.Data;
+
+namespace Anubis.Tests;
+
+///
+/// Builders of hand-made market data for the basket engine (Phase 14): daily bars on the currency weekdays, 15-minute bars
+/// with explicit bid and ask, the 28 crosses of seven synthetic rates, and log series that revert or walk.
+///
+internal static class BasketSynthetic
+{
+ /// A Monday in winter, far from any change of the clocks.
+ public static readonly DateOnly Monday = new(2026, 1, 5);
+
+ /// The first currency weekdays from (Monday to Friday).
+ public static IReadOnlyList Weekdays(DateOnly start, int count)
+ {
+ var days = new List(count);
+ for (var day = start; days.Count < count; day = day.AddDays(1))
+ {
+ if (day.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday))
+ {
+ days.Add(day);
+ }
+ }
+
+ return days;
+ }
+
+ ///
+ /// Daily bars like the ECB's (open = high = low = close, at 00:00 UTC of each weekday from ), one
+ /// reference price a day and no ask: the engine builds bid and ask with the venue's spread.
+ ///
+ public static BarDataset Daily(IReadOnlyDictionary closes, DateOnly? start = null)
+ {
+ var length = closes.Values.Max(c => c.Length);
+ var days = Weekdays(start ?? Monday, length);
+ var bars = closes.ToDictionary(
+ p => p.Key,
+ p => (IReadOnlyList)[.. p.Value.Select((c, i) => Flat(Midnight(days[i]), c))],
+ StringComparer.Ordinal);
+ return BarDataset.Build(Timeframes.Day, BarCalendars.Fx, Midnight(days[0]), Midnight(days[^1]).AddDays(1), bars);
+ }
+
+ ///
+ /// 15-minute bars from , one per entry of , with the ask given beside each
+ /// bid (open, high, low, close of both sides).
+ ///
+ public static BarDataset Quarters(DateTimeOffset first, IReadOnlyDictionary quotes)
+ {
+ var bids = new Dictionary>(StringComparer.Ordinal);
+ var asks = new Dictionary>(StringComparer.Ordinal);
+ var length = 0;
+ foreach (var (symbol, rows) in quotes)
+ {
+ bids[symbol] = [.. rows.Select((r, i) => r.Bid.Bar(first.AddMinutes(15 * i)))];
+ asks[symbol] = [.. rows.Select((r, i) => r.Ask.Bar(first.AddMinutes(15 * i)))];
+ length = Math.Max(length, rows.Length);
+ }
+
+ return BarDataset.Build(Timeframes.Minutes15, BarCalendars.Fx, first, first.AddMinutes(15 * length), bids, asks);
+ }
+
+ /// A quote whose four prices are one mid, with the bid half a spread below and the ask half above.
+ public static (QuoteSide Bid, QuoteSide Ask) Mid(decimal mid, decimal spread) => (QuoteSide.Flat(mid - (spread / 2)), QuoteSide.Flat(mid + (spread / 2)));
+
+ /// The 28 ECB-like crosses of seven synthetic rates against the euro, one fixing a weekday.
+ public static BarDataset Crosses(int days, int seed, double halfLife = 50, double volatility = 0.005, DateOnly? start = null)
+ {
+ var dates = Weekdays(start ?? new DateOnly(2020, 1, 6), days);
+ var levels = new Dictionary(StringComparer.Ordinal)
+ {
+ ["GBP"] = 0.86,
+ ["AUD"] = 1.62,
+ ["NZD"] = 1.78,
+ ["USD"] = 1.10,
+ ["CAD"] = 1.48,
+ ["CHF"] = 0.97,
+ ["JPY"] = 150,
+ };
+ var rates = new List();
+ var k = 0;
+ foreach (var (currency, level) in levels)
+ {
+ var path = Reverting(days, Synthetic.Phi(halfLife), seed + (k++ * 7919), volatility);
+ rates.AddRange(dates.Select((d, i) => new FxRate(Currencies.Eur, currency, d, Math.Round((decimal)(level * Math.Exp(path[i])), 6), "ecb")));
+ }
+
+ var crosses = EcbCrosses.Build(rates);
+ return BarDataset.Build(Timeframes.Day, BarCalendars.Fx, Midnight(dates[0]), Midnight(dates[^1]).AddDays(1), crosses);
+ }
+
+ /// A log series that reverts to zero: s(t) = φ·s(t−1) + σ·ε, from zero.
+ public static double[] Reverting(int bars, double phi, int seed, double volatility = 0.01)
+ {
+ var random = new Gen(seed);
+ var s = new double[bars];
+ for (var t = 1; t < bars; t++)
+ {
+ s[t] = (phi * s[t - 1]) + (volatility * random.Normal());
+ }
+
+ return s;
+ }
+
+ /// A log series that walks: s(t) = s(t−1) + drift + σ·ε, from zero.
+ public static double[] Walk(int bars, int seed, double drift = 0, double volatility = 0.01)
+ {
+ var random = new Gen(seed);
+ var s = new double[bars];
+ for (var t = 1; t < bars; t++)
+ {
+ s[t] = s[t - 1] + drift + (volatility * random.Normal());
+ }
+
+ return s;
+ }
+
+ /// Prices that alternate between two levels for bars: a window with a known spread.
+ public static IEnumerable Alternate(double low, double high, int count) => Enumerable.Range(0, count).Select(i => i % 2 == 0 ? low : high);
+
+ public static DateTimeOffset Midnight(DateOnly day) => new(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero);
+
+ private static ResearchBar Flat(DateTimeOffset at, double close)
+ {
+ var price = (decimal)close;
+ return new ResearchBar(at, price, price, price, price, 0m);
+ }
+}
+
+/// Open, high, low and close of one side of a quote.
+internal readonly record struct QuoteSide(decimal Open, decimal High, decimal Low, decimal Close)
+{
+ public static QuoteSide Flat(decimal price) => new(price, price, price, price);
+
+ public ResearchBar Bar(DateTimeOffset at) => new(at, Open, High, Low, Close, 0m);
+}