Files
Anubis/tests/Anubis.Tests/BasketEngineTests.cs
T
Alby96andClaude Opus 5.5 a8defde572 Fix the review findings of the basket engine, command and report
The independent review of Phase 14 found rules the engine applied
differently from the decisions, numbers the report labelled wrongly and
a command that left a trial "running" when interrupted.

Engine:
- The pause after the 9% account stop is read at the decision moment
  (the bar's close), like every other gate: on daily bars it no longer
  blocks one day past the server date change.
- In a one-pair basket, a level closed by the venue's mandatory stop
  closes the other levels at the next execution with their own reason,
  closed_with_stop (counted and labelled in the report); the basket's
  exit stays mandatory_stop, and a two-leg basket keeps orphan_leg.
- The cap of two entries per currency applies to new baskets only,
  never to the averagings of an open basket, and every leg is valued
  at the current mid: a Prudente long basket "come dal vivo" now makes
  its three averagings and Fedele writes no note on them.
- The surrogate of the control chains on the mid when the source has
  an ask, so each mid change keeps its size and the spread stays
  around the mid instead of moving the mid by a spread at each change
  of sign.
- The financing already charged on positions still open at the end is
  part of the run's fees (BacktestRun.AccruedFees, zero for the daily
  engine, kept in stored unit outcomes).

Report: the fee row says what it holds (commission and financing, the
spread is in the prices) and the cost-stress text matches what the
multiplier scales; baskets still open at the end are labelled as such
and left out of the share closed at the target; refusal labels say
what the engine checks; the ECB-price and cost limitations are no
longer printed twice; every count has the Italian thousands separator.

Command: Ctrl+C or SIGTERM cancels the run; the trial is recorded as
failed with "Prova interrotta prima della fine: rilancia «anubis
backtest baskets»." and the command exits 1; a trial that cannot start
is failed instead of thrown, and an unexpected error ends with an
Italian line, never a stack trace. The laboratory fails a leftover
basket trial with an accurate message instead of "Strategia non più
disponibile".

The Table 6.5 test comment no longer claims each price is the only one
that fits the row. The real report is regenerated on the same data and
database as the first run, which now counts as a prior trial.

refs #127 #129 #131

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 19:26:24 +01:00

542 lines
32 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 OnDailyBarsTheAccountStopPausesOnlyUntilTheServerDateChanges()
{
// Daily fixings at 00:00 UTC from Monday 5 January 2026, no spread and no cost. 100,000 EURUSD bought at 1.0000 on
// Tuesday 20 (bar 11); Wednesday's bar (12) closes at 0.9910, on Thursday 22 at 00:00 UTC: open loss 900 / 10,000 = 9%,
// the account stop fires. That moment is Wednesday 19:00 in New York, already server day Thursday, so the pause lasts
// until Thursday 17:00 New York, 22:00 UTC. Thursday's bar (13) is decided at its close, Friday 00:00 UTC, after the
// change: its signal (0.9800, z = −2.57) opens.
double[] e = [.. BasketSynthetic.Alternate(1.0000, 1.0001, 10), 0.9990, 1.0000, 0.9910, 0.9800, 0.9800];
var data = BasketSynthetic.Daily(new Dictionary<string, double[]> { ["EURUSD"] = e });
var result = Run(data, SingleRules(EurUsd, BasketMode.AsDocument) with { LotPer10k = 1m }, VenueCosts.None);
var stop = result.Events.Single(x => x.Reason == BasketReasons.AccountStop);
Assert.AreEqual(BasketSynthetic.Midnight(new DateOnly(2026, 1, 22)), stop.At, "at the close of Wednesday's bar");
Assert.AreEqual(new DateTimeOffset(2026, 1, 22, 22, 0, 0, TimeSpan.Zero), ServerClock.NextDayStart(stop.At));
Assert.IsFalse(result.Events.Any(x => x.Reason == BasketReasons.PausedUntilNextDay), "Thursday's decision comes after the change");
var reopened = result.Events.Single(x => x.Kind == BasketEventKinds.Open && x.At > stop.At);
Assert.AreEqual(BasketSynthetic.Midnight(new DateOnly(2026, 1, 23)), reopened.At, "Thursday's signal opens at its close");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AMandatoryStopOnOneLevelOfASinglePairBasketClosesTheOtherLevelsWithTheirOwnReason()
{
// EURUSD (spread 0.1 pip) signals on Monday 19 January 2026 and is bought on Tuesday at the ask 0.998505; Wednesday
// closes at 0.9900, 86 pips under it with z = −2.78: an averaging, bought on Thursday at 0.989005. The venue's stops
// at leverage 5 sit 10% under each entry: 0.8986545 and 0.8901045. Friday fixes at 0.8950, bid 0.894995: level 0's
// stop is gone through at the open, level 1's is not. The basket's exit is the mandatory stop; level 1 closes at the
// next execution as closed with it, not as a stop of its own, and nothing is an orphan leg (one pair).
double[] e = [.. BasketSynthetic.Alternate(1.0000, 1.0002, 10), 0.9985, 0.9985, 0.9900, 0.9890, 0.8950, 0.8950, 0.8950];
var data = BasketSynthetic.Daily(new Dictionary<string, double[]> { ["EURUSD"] = e });
var result = Run(data, SingleRules(EurUsd, BasketMode.AsDocument) with { Distance = 50m }, VenueCosts.Etoro);
var trace = result.Traces.Single();
Assert.AreEqual(2, trace.Levels);
Assert.AreEqual(BasketReasons.MandatoryStop, trace.ExitReason);
Assert.AreEqual(BasketReasons.MandatoryStop, result.Run.Baskets.Single().ExitReason);
CollectionAssert.AreEqual(new[] { BasketReasons.MandatoryStop, BasketReasons.ClosedWithStop }, trace.Positions.Select(p => p.ExitReason).ToArray());
CollectionAssert.AreEqual(new int?[] { 14, 15 }, trace.Positions.Select(p => p.ExitBar).ToArray());
Assert.AreEqual(0.894995m, trace.Positions[0].ExitPrice, "the bid of Friday's open");
Assert.AreEqual(1, result.Run.Fills.Count(f => f.Reason == BasketReasons.ClosedWithStop));
Assert.AreEqual(1, result.Run.Notes.Count(n => n.Reason == BasketReasons.MandatoryStop));
Assert.AreEqual(1, result.Run.Notes.Count(n => n.Reason == BasketReasons.ClosedWithStop));
Assert.AreEqual(0, result.Run.Notes.Count(n => n.Reason == BasketReasons.OrphanLeg));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheFeesOfARunIncludeTheFinancingOfPositionsStillOpen()
{
// EURUSD bought on Tuesday 20 January 2026 at 1.098505 and never sold: still open at the end. Its financing has left the
// cash at every rollover, so it is in the fees of the run although no closing fill carries it.
double[] e = [.. BasketSynthetic.Alternate(1.1000, 1.1002, 10), .. Enumerable.Repeat(1.0985, 10)];
var data = BasketSynthetic.Daily(new Dictionary<string, double[]> { ["EURUSD"] = e });
var result = Run(data, SingleRules(EurUsd, BasketMode.AsDocument), VenueCosts.Etoro);
Assert.AreEqual(BasketReasons.End, result.Run.Baskets.Single().ExitReason);
Assert.IsTrue(result.Financing > 0m, $"financing {result.Financing}");
Assert.AreEqual(result.Commission + result.Financing, result.Run.Fees);
Assert.AreEqual(result.Run.Fills.Sum(f => f.Fee) + result.Financing, result.Run.Fees, "one opening fill: its commission, plus the financing");
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AsLiveTheCurrencyCapStopsNewBasketsNotTheAveragingsOfAnOpenOne()
{
// 10,000 EURUSD (100,000 of capital) bought at 0.9985, then three averagings 15 pips apart or more, each with z ≤ −2:
// at 0.9960 (z −2.47), 0.9930 (−2.12) and 0.9860 (−2.26). Long EURUSD alone is long euro and short dollar, two entries
// and more once averaged: the cap of two entries per currency is for a new basket (plan, section 5), never for the
// levels of one already open. Prudente makes its three averagings; Fedele writes no note about them.
double[] e = [.. BasketSynthetic.Alternate(1.0000, 1.0002, 10), 0.9985, 0.9985, 0.9960, 0.9960, 0.9930, 0.9930, 0.9860, 0.9860, 0.9860];
var data = BasketSynthetic.Daily(new Dictionary<string, double[]> { ["EURUSD"] = e });
foreach (var profile in BasketProfiles.All)
{
var result = Run(data, SingleRules(EurUsd, BasketMode.AsLive) with { Distance = 15m, Profile = profile }, VenueCosts.None, 100_000m);
var trace = result.Traces.Single();
Assert.AreEqual(4, trace.Levels, profile.Name);
CollectionAssert.AreEqual(new[] { 11, 13, 15, 17 }, trace.Positions.Select(p => p.EntryBar).ToArray(), profile.Name);
Assert.AreEqual(0, result.Events.Count(x => x.Reason == BasketReasons.CurrencyExposure), profile.Name);
Assert.AreEqual(0, result.Run.Notes.Count(n => n.Reason == BasketReasons.CurrencyExposure), profile.Name);
}
}
[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);
}