Add the basket engine: a margin account that trades the document's baskets

Phase 14 needs an engine that simulates the research document's baskets
with the frictions of the venue, so the trial judge can say whether they
earn anything once those frictions are paid.

BasketEngine walks a BasketMarket (the bars of a BarDataset without the
moments no symbol trades) bar by bar: decisions on the closed bar,
execution at the next open, buys at the ask and sells at the bid (bid and
ask rebuilt from the venue spread when the source gives one price, as the
ECB fixings do). Every leg of every level is its own position with the
venue's mandatory stop; a stop that leaves one leg of a two-leg basket
alone closes the rest at the next execution as an orphan leg. Commission
on both sides, financing at every rollover crossed (Wednesday triple, from
the VenueCosts calendar), liquidation below half the initial margin.

On top, the document's account rules (9% stop on the open loss over the
balance, on mid prices in the daily pause, entries back at the next server
day; 2% gate on new baskets only; open baskets, Rvol, correlation, three
costs) and, «come dal vivo», SPEC 9.2 through RiskMonitor (day, week, fall
from the high, trip with the seven-day restart), the 40% margin limit,
nine positions, no opposite positions, net exposure per currency and the
Prudente basket stops. One equity point a day for every variant.

Signals come from the replica's RollingZ and RollingSigma on each unit's
compressed series; a rolling Rvol joins them, equal to BasketIndex.Rvol.
The comparison configuration (same close, no cost, no protection) makes
the replica's baskets on 200 seeded series and its total to 1e-9; on the
ECB fixture it gives the replica's 535.54 targets over 1,259 baskets.
TrialPlan gains optional Mode and Costs, left out when null, so the plans
of the daily families keep their hashes.

refs #127

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-04 18:17:13 +01:00
1 parent 63bd5b9635
commit 44639e3f49
10 files changed
+2631

No files matched your search

+159
View File
@@ -0,0 +1,159 @@
using System.Collections.Concurrent;
using Anubis.Baskets;
namespace Anubis.Backtest;
/// <summary>
/// Why a basket closed and why a decision was refused or noted (<see cref="BacktestNote.Reason"/>,
/// <see cref="BacktestBasket.ExitReason"/>, <see cref="BasketEvent.Reason"/>): the report counts them.
/// </summary>
public static class BasketReasons
{
// Exits.
public const string Target = "target";
/// <summary>The Prudente basket stop, or the replica's stop in targets in the comparison configuration.</summary>
public const string StopBasket = "stop_basket";
/// <summary>The 9% stop on the open loss over the balance: everything closes.</summary>
public const string AccountStop = "account_stop";
/// <summary>The venue's stop on one position, at most at half its margin.</summary>
public const string MandatoryStop = "mandatory_stop";
/// <summary>The leg left alone when the other leg's mandatory stop closed: it closes at the next execution.</summary>
public const string OrphanLeg = "orphan_leg";
/// <summary>The venue closed everything: the equity fell below half the initial margin of the open positions.</summary>
public const string Liquidation = "liquidation";
/// <summary>Still open at the end of the data, valued at the last marks.</summary>
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";
/// <summary>Nine positions open on the account (plan, section 9): not the daily engine's position_limit, a weight cap.</summary>
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";
/// <summary>The weekend, the daily pause or the hourly window, on bars shorter than a day.</summary>
public const string ClockWindow = "clock_window";
}
/// <summary>The kinds of <see cref="BasketEvent"/>.</summary>
public static class BasketEventKinds
{
public const string Open = "open";
public const string Add = "add";
public const string Close = "close";
public const string Refused = "refused";
/// <summary>Something written down without changing the decision (Fedele's cost rule, a halved size).</summary>
public const string Note = "note";
}
/// <summary>
/// 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 <see cref="At"/> allows: the look-ahead check compares them on cut data.
/// </summary>
public sealed record BasketEvent(DateTimeOffset At, DateOnly Day, string Unit, string Kind, string Reason, int Direction);
/// <summary>
/// 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.
/// </summary>
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);
/// <summary>
/// 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.
/// </summary>
public sealed record BasketTrace(int Id, string Unit, int Direction, double Sigma, IReadOnlyList<BasketPositionTrace> Positions, int? ExitBar, string ExitReason)
{
public int Levels => Positions.Select(p => p.Level).Distinct().Count();
}
/// <summary>
/// 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).
/// </summary>
public sealed record BasketRunResult(BacktestRun Run, IReadOnlyList<BasketTrace> Traces, IReadOnlyList<BasketEvent> Events, decimal Commission, decimal Financing);
/// <summary>
/// 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 <see cref="BasketMarket"/>. 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.
/// </summary>
public sealed class BasketEngine
{
/// <summary>Changes when the engine computes differently: basket plans record it in their <c>engine</c> field.</summary>
public const string Version = "basket-1";
/// <summary>The symbol of the notes about the whole account (account stop, liquidation).</summary>
public const string AccountSymbol = "conto";
private readonly ConcurrentDictionary<string, Lazy<object>> _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; }
/// <summary>
/// One run of <paramref name="rules"/> with costs multiplied by <paramref name="costMultiplier"/> (spread, commission and
/// financing paid), trading and measuring the days from <paramref name="from"/> to <paramref name="to"/> (both included;
/// null: the whole market). Bars before <paramref name="from"/> only warm the signals up.
/// </summary>
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();
}
/// <summary>A value computed once per engine and key (the signals of a unit): immutable, shared by every run.</summary>
internal T Cached<T>(string key, Func<T> compute)
where T : class => (T)_cache.GetOrAdd(key, _ => new Lazy<object>(() => compute())).Value;
}
+252
View File
@@ -0,0 +1,252 @@
using Anubis.Baskets;
using Anubis.Data;
namespace Anubis.Backtest;
/// <summary>Open, high, low and close of one side of a series on the market clock: not a number where it has no bar.</summary>
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]);
}
/// <summary>
/// The prices the basket engine trades on (Phase 14): the bars of a <see cref="BarDataset"/> 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.
/// </summary>
public sealed class BasketMarket
{
private readonly DateTimeOffset[] _clock;
private readonly DateOnly[] _days;
private readonly Dictionary<string, PriceColumns> _bids;
private readonly Dictionary<string, PriceColumns> _asks;
private BasketMarket(string timeframe, DateTimeOffset[] clock, Dictionary<string, PriceColumns> bids, Dictionary<string, PriceColumns> 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; }
/// <summary>Bars of a day or longer: the time-of-day windows of the document do not apply to them.</summary>
public bool Daily => Length >= TimeSpan.FromDays(1);
/// <summary>The opening moments of the bars, oldest first, in UTC.</summary>
public IReadOnlyList<DateTimeOffset> Clock => _clock;
public int Count => _clock.Length;
/// <summary>The symbols, in ordinal order.</summary>
public IReadOnlyList<string> Symbols { get; }
/// <summary>The fingerprint of the data the market was built from (<see cref="BarDataset.Fingerprint"/>), marked when cut or flipped.</summary>
public string Fingerprint { get; }
/// <summary>The market of a dataset: the moments where no symbol has a bar are left out.</summary>
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<string, PriceColumns>(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);
/// <summary>Whether the symbol has a bar at position <paramref name="t"/>.</summary>
public bool Has(string symbol, int t) => _bids.TryGetValue(symbol, out var columns) && !double.IsNaN(columns.Close[t]);
/// <summary>Whether the source gives the ask of the symbol: otherwise bid and ask are built around one reference price.</summary>
public bool HasAsk(string symbol) => _asks.ContainsKey(symbol);
/// <summary>When the bar at <paramref name="t"/> closes.</summary>
public DateTimeOffset ClosesAt(int t) => _clock[t] + Length;
/// <summary>The day of the equity point the bar at <paramref name="t"/> belongs to.</summary>
public DateOnly Day(int t) => _days[t];
/// <summary>
/// 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.
/// </summary>
public IReadOnlyList<double> 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)];
}
/// <summary>The bars that have closed by <paramref name="moment"/>: what a decision taken then could know.</summary>
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'}");
}
/// <summary>
/// The surrogate of the control against chance (<see cref="Surrogates"/>): 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
/// <paramref name="centred"/>). 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.
/// </summary>
public BasketMarket Surrogate(DaySigns signs, bool centred)
{
ArgumentNullException.ThrowIfNull(signs);
var bids = new Dictionary<string, PriceColumns>(StringComparer.Ordinal);
var asks = new Dictionary<string, PriceColumns>(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;
}
}
+233
View File
@@ -0,0 +1,233 @@
using System.Globalization;
using Anubis.Baskets;
namespace Anubis.Backtest;
/// <summary>
/// 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).
/// </summary>
public enum BasketMode
{
/// <summary>«alla lettera»: the rules of the research document only.</summary>
AsDocument,
/// <summary>«come dal vivo»: the document's rules and every limit the live bot would have.</summary>
AsLive,
}
/// <summary>The names of the modes in plans and reports.</summary>
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;
/// <summary>The mode a plan names; throws, in Italian, on an unknown name.</summary>
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)),
};
}
/// <summary>When a decision taken on a closed bar is executed.</summary>
public enum BasketExecution
{
/// <summary>At the next bar's open, buying at the ask and selling at the bid (the plan's convention).</summary>
NextOpen,
/// <summary>At the same close: only the comparison configuration with the replica of appendix G.</summary>
SameClose,
}
/// <summary>The index the z-score reads (sections 4.3 and 11.3).</summary>
public enum BasketSignal
{
/// <summary>The pip index X = A / pip(A) + s · B / pip(B).</summary>
ZScorePipSum,
/// <summary>The log index X = 10,000 · (ln A + s · ln B), in basis points.</summary>
ZScoreLog,
}
/// <summary>The unit of target and averaging distance: pips, or σ of the index frozen at the opening (section 11.3).</summary>
public enum BasketMeasure
{
Pips,
Sigma,
}
/// <summary>When a basket reaches its target.</summary>
public enum BasketExitRule
{
/// <summary>Section 4.5: the pips of every open order, added, reach the target.</summary>
PipSum,
/// <summary>Appendix G.3: the index is beyond the mean of the entries by the target.</summary>
MeanOfEntries,
}
/// <summary>
/// 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.
/// </summary>
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<FxPair> Legs => B is null ? [A] : [A, B];
/// <summary>The fixed sign of the index, or null for a disjoint couple (its sign comes from the correlation).</summary>
public int? FixedSign => Kind switch
{
RelationKind.SingleSymbol => 1,
RelationKind.Disjoint => null,
_ => Relations.Sign(Kind, null),
};
}
/// <summary>
/// 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.
/// </summary>
public sealed record BasketRules(IReadOnlyList<BasketUnit> Units)
{
public BasketSignal Signal { get; init; } = BasketSignal.ZScorePipSum;
/// <summary>Bars of the z-score and σ window, bar t included.</summary>
public int Window { get; init; } = BasketIndex.DefaultWindow;
public double EntryZ { get; init; } = 2.0;
public BasketMeasure Measure { get; init; } = BasketMeasure.Pips;
/// <summary>The target, in pips or in σ.</summary>
public decimal Target { get; init; } = 10m;
/// <summary>The smallest averaging distance from the last level, in pips or in σ.</summary>
public decimal Distance { get; init; } = 40m;
/// <summary>The growth of the distance at each averaging (1.3 in the growing variant).</summary>
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;
/// <summary>Lots per 10,000 of initial capital, the same on every leg and every level.</summary>
public decimal LotPer10k { get; init; } = 0.01m;
/// <summary>The leverage of each position, never above the pair's on the real account.</summary>
public int Leverage { get; init; } = 5;
public BasketMode Mode { get; init; } = BasketMode.AsLive;
public BasketExecution Execution { get; init; } = BasketExecution.NextOpen;
/// <summary>The document's account rules (9% stop, 2% gate, open baskets, cost rule): off only for the comparison configuration.</summary>
public bool Protections { get; init; } = true;
/// <summary>The basket stop of the replica, in targets: comparison configuration only.</summary>
public double? StopTargets { get; init; }
/// <summary>The correlation a two-leg unit needs on its expected sign to open; null turns the check off.</summary>
public double? MinCorrelation { get; init; } = 0.6;
/// <summary>Above this Rvol no basket opens; null turns the filter and the distance factor off.</summary>
public double? MaxRvol { get; init; } = BasketIndex.DefaultMaxRvol;
/// <summary>A unit opens only if its target is at least this many times its round-trip cost (section 11.3).</summary>
public decimal CostMultiple { get; init; } = BasketMath.CostMultiple;
/// <summary>The hourly window 10:00–20:00 server time on bars shorter than a day (on in generation B).</summary>
public bool Session { get; init; }
/// <summary>The weekend, the daily pause and the hourly window on bars shorter than a day: on unless a test turns them off.</summary>
public bool ClockWindows { get; init; } = true;
/// <summary>Differences in the short window of Rvol.</summary>
public int ShortBars { get; init; } = BasketIndex.DefaultShortBars;
/// <summary>Bars of the Rvol baseline; null: 20 market days of the timeframe (20 bars on daily bars).</summary>
public int? BaselineBars { get; init; }
/// <summary>A test hook: the signal of bar t reads bar t + shift. Never set outside the look-ahead test.</summary>
internal int SignalShift { get; init; }
/// <summary>
/// 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 <see cref="VenueCosts.None"/>.
/// </summary>
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,
};
}
/// <summary>Checks the values; the message is for the user.</summary>
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.");
}
}
}
+100
View File
@@ -0,0 +1,100 @@
using Anubis.Baskets;
namespace Anubis.Backtest;
/// <summary>
/// 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. <see cref="Position"/> 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.
/// </summary>
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<int>(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; }
/// <summary>The market bar of each point of the series.</summary>
public int[] Bars { get; }
/// <summary>The point of the series of each market bar, −1 when a leg has no bar.</summary>
public int[] Position { get; }
public double[] PricesA { get; }
public double[]? PricesB { get; }
/// <summary>The index of the signal at prices <paramref name="a"/> and <paramref name="b"/> with sign <paramref name="sign"/>.</summary>
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),
};
/// <summary>The pip index, whatever the signal: targets and distances in pips with the exit on the mean of the entries read it.</summary>
public double PipIndex(int sign, double a, double b) => Index(BasketSignal.ZScorePipSum, sign, a, b);
/// <summary>The correlation of the log returns of the two legs over the window ending at point <paramref name="c"/>; null for one leg.</summary>
public double? Correlation(int c, int window) => PricesB is null ? null : BasketIndex.Correlation(PricesA, PricesB, c, window);
}
/// <summary>
/// The signals of a unit with one index and one sign: the index, z and σ from the shared rolling functions of the replica
/// (<see cref="BasketIndex.RollingZ"/>, <see cref="BasketIndex.RollingSigma"/>), Rvol (<see cref="BasketIndex.RollingRvol"/>)
/// when the filter is on, and the pip index. One value per point of the compressed series.
/// </summary>
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; }
}
File diff suppressed because it is too large. Load diff
+9
View File
@@ -85,6 +85,15 @@ public sealed record TrialPlan(
/// </summary> /// </summary>
public string? Judged { get; init; } public string? Judged { get; init; }
/// <summary>
/// The mode of a basket trial (<see cref="BasketModes"/>): «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.
/// </summary>
public string? Mode { get; init; }
/// <summary>The venue's costs a basket trial runs with, with their date and source; null for the daily families.</summary>
public VenueCosts? Costs { get; init; }
public static readonly JsonSerializerOptions Json = new() public static readonly JsonSerializerOptions Json = new()
{ {
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
+72
View File
@@ -289,6 +289,78 @@ public static class BasketIndex
return baseline > 0 ? current / baseline : null; return baseline > 0 ? current / baseline : null;
} }
/// <summary>
/// <see cref="Rvol"/> at every bar in one pass (Phase 14, as ADR 0028 asked): σ_short of every bar once, then the median of
/// the last <paramref name="baselineBars"/> 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 <see cref="Rvol"/>, bit for bit; not a number where it is null.
/// </summary>
public static double[] RollingRvol(IReadOnlyList<double> 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--;
}
}
/// <summary>The volatility filter: a new entry only with a known Rvol no higher than <paramref name="max"/>.</summary> /// <summary>The volatility filter: a new entry only with a known Rvol no higher than <paramref name="max"/>.</summary>
public static bool AllowsEntry(double? rvol, double max = DefaultMaxRvol) => rvol is { } r && r <= max; public static bool AllowsEntry(double? rvol, double max = DefaultMaxRvol) => rvol is { } r && r <= max;
+22
View File
@@ -102,6 +102,28 @@ public static class ReasonCatalog
["restart"] = "Annullato alla ripartenza del bot: se era ancora dovuto, è stato riproposto.", ["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.", ["protected_restart"] = "Deciso prima del ripristino: non parte, potrebbe essere già partito allora.",
["recovered"] = "Recuperato dopo un'assenza.", ["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; public static string Text(string code) => Texts.TryGetValue(code, out var text) ? text : code;
+452
View File
@@ -0,0 +1,452 @@
using Anubis.Backtest;
using Anubis.Baskets;
using Anubis.Data;
namespace Anubis.Tests;
/// <summary>
/// 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.
/// </summary>
[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<string, (QuoteSide, QuoteSide)[]>
{
["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<string, (QuoteSide, QuoteSide)[]> { ["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<string, (QuoteSide, QuoteSide)[]> { ["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<string, double[]> { ["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<string, double[]> { ["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<string, double[]> { ["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);
/// <summary>A single symbol of generation B on a 10-bar window: 10 pips of target, averaging too far to happen.</summary>
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<string, double[]> { ["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<string, double[]> { ["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<string, double>(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<string, double[]> { ["EURUSD"] = e });
}
private static IEnumerable<decimal> 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);
}
+138
View File
@@ -0,0 +1,138 @@
using Anubis.Backtest;
using Anubis.Baskets;
using Anubis.Data;
namespace Anubis.Tests;
/// <summary>
/// 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.
/// </summary>
internal static class BasketSynthetic
{
/// <summary>A Monday in winter, far from any change of the clocks.</summary>
public static readonly DateOnly Monday = new(2026, 1, 5);
/// <summary>The first <paramref name="count"/> currency weekdays from <paramref name="start"/> (Monday to Friday).</summary>
public static IReadOnlyList<DateOnly> Weekdays(DateOnly start, int count)
{
var days = new List<DateOnly>(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;
}
/// <summary>
/// Daily bars like the ECB's (open = high = low = close, at 00:00 UTC of each weekday from <paramref name="start"/>), one
/// reference price a day and no ask: the engine builds bid and ask with the venue's spread.
/// </summary>
public static BarDataset Daily(IReadOnlyDictionary<string, double[]> 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<ResearchBar>)[.. 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);
}
/// <summary>
/// 15-minute bars from <paramref name="first"/>, one per entry of <paramref name="bids"/>, with the ask given beside each
/// bid (open, high, low, close of both sides).
/// </summary>
public static BarDataset Quarters(DateTimeOffset first, IReadOnlyDictionary<string, (QuoteSide Bid, QuoteSide Ask)[]> quotes)
{
var bids = new Dictionary<string, IReadOnlyList<ResearchBar>>(StringComparer.Ordinal);
var asks = new Dictionary<string, IReadOnlyList<ResearchBar>>(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);
}
/// <summary>A quote whose four prices are one mid, with the bid half a spread below and the ask half above.</summary>
public static (QuoteSide Bid, QuoteSide Ask) Mid(decimal mid, decimal spread) => (QuoteSide.Flat(mid - (spread / 2)), QuoteSide.Flat(mid + (spread / 2)));
/// <summary>The 28 ECB-like crosses of seven synthetic rates against the euro, one fixing a weekday.</summary>
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<string, double>(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<FxRate>();
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);
}
/// <summary>A log series that reverts to zero: s(t) = φ·s(t−1) + σ·ε, from zero.</summary>
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;
}
/// <summary>A log series that walks: s(t) = s(t−1) + drift + σ·ε, from zero.</summary>
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;
}
/// <summary>Prices that alternate between two levels for <paramref name="count"/> bars: a window with a known spread.</summary>
public static IEnumerable<double> 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);
}
}
/// <summary>Open, high, low and close of one side of a quote.</summary>
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);
}