Add the basket maths: server clock, relations, index, money rules, states

Pure code in src/Anubis/Baskets for the basket reversion family of the new
route, so the engine of phase 14 and the eToro Demo of phase 20 share one
home for the arithmetic of the research document:

- ServerClock: New York + 7 h, the server day changing at 17:00 New York,
  half-open weekend rule, hourly window and daily venue pause.
- Relations: chain, ratio and disjoint couples (56 + 112 + 210 = 378),
  appendix B in the document's row order, the eight documented spreads,
  the index sign and the 14-pair list.
- BasketIndex: pip and log basis-point index, sample z-score, Rvol with
  its filter, correlation of log returns and the OLS hedge ratio; every
  value at bar t reads bars up to t only.
- BasketMath (decimal): pip sum, common exit, distance scale with no
  addition after the last level, stop excursion of table 4.12, pip value,
  equal units raised to the venue minimum, exposure, three-costs rule.
- Styles: pair states, the four styles, the Fedele and Prudente profiles.

Every acceptance criterion of the item has a named test with the
document's numbers, plus a fixed-seed property test that nothing at a
closed bar depends on later bars.

refs #119

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-12-04 10:06:44 +01:00
1 parent f895c54076
commit aec848b4a2
9 files changed
+1884

No files matched your search

+278
View File
@@ -0,0 +1,278 @@
using System.Globalization;
using Anubis.Baskets;
namespace Anubis.Tests;
/// <summary>
/// The money side of the basket maths (Phase 12, issue #119): pip sum and common exit, table 4.5, the distance scale, the
/// stop excursions of table 4.12 and section 6.9, pip value, units raised to the venue minimum, exposure and the three-costs
/// rule. Every expected number is the document's, or worked out by hand in the comment next to it.
/// </summary>
[TestClass]
public sealed class BasketMathTests
{
private static readonly decimal[] AudusdEntries = [0.69456m, 0.69003m, 0.68739m];
[TestMethod]
[TestCategory(Category.Unit)]
public void ThreeAudusdBuysWithTarget69ExitAtTheCommonPrice()
{
var pair = FxPairs.Get("AUDUSD");
// mean = 2.07198 / 3 = 0.69066; target / n = 6.9 / 3 = 2.3 pips = 0.00023; P* = 0.69089.
var exit = BasketMath.CommonExit(AudusdEntries, Direction.Buy, 6.9m, pair.Pip);
Assert.IsTrue(Math.Abs(exit - 0.69089m) <= 0.1m * pair.Pip, exit.ToString(CultureInfo.InvariantCulture));
// At that bid each order has −36.7, +8.6 and +35.0 pips, +6.9 in all.
var quote = new BidAsk(0.69089m, 0.69095m);
var orders = AudusdEntries.Select(e => new BasketOrder(pair, Direction.Buy, e)).ToArray();
CollectionAssert.AreEqual(new[] { -36.7m, 8.6m, 35.0m }, orders.Select(o => o.Pips(quote)).ToArray());
Assert.AreEqual(6.9m, BasketMath.PipSum(orders, _ => quote));
Assert.AreEqual(6.9m, BasketMath.PipSum(orders, _ => new BidAsk(exit, exit + 0.00006m)));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ShortOrdersExitBelowTheMeanAndCountPipsOnTheAsk()
{
var pair = FxPairs.Get("USDJPY");
decimal[] entries = [157.20m, 157.60m, 158.00m];
// mean 157.60, target 9 over 3 orders = 3 pips = 0.03 below: 157.57.
var exit = BasketMath.CommonExit(entries, Direction.Sell, 9m, pair.Pip);
Assert.AreEqual(157.57m, exit);
var orders = entries.Select(e => new BasketOrder(pair, Direction.Sell, e)).ToArray();
Assert.AreEqual(9m, BasketMath.PipSum(orders, _ => new BidAsk(157.55m, exit)));
CollectionAssert.AreEqual(new[] { -37m, 3m, 43m }, orders.Select(o => o.Pips(new BidAsk(157.55m, exit))).ToArray());
}
[TestMethod]
[TestCategory(Category.Unit)]
[DataRow(1, "10.00")]
[DataRow(2, "5.00")]
[DataRow(3, "3.33")]
[DataRow(4, "2.50")]
[DataRow(5, "2.00")]
[DataRow(8, "1.25")]
public void TheMovePerOrderFollowsTable45(int orders, string expected)
{
var move = BasketMath.MovePerOrder(10m, orders);
Assert.AreEqual(decimal.Parse(expected, CultureInfo.InvariantCulture), Math.Round(move, 2));
// The same identity as the common exit: P* − mean = target / n pips.
var entries = Enumerable.Range(0, orders).Select(i => 1.1000m - (i * 0.0040m)).ToArray();
var exit = BasketMath.CommonExit(entries, Direction.Buy, 10m, 0.0001m);
AssertClose(move * 0.0001m, exit - entries.Average(), 0.0000000000000000001m);
}
[TestMethod]
[TestCategory(Category.Unit)]
[DataRow(0.8, "1.0", "40", "40", "40", "40")]
[DataRow(0.8, "1.3", "40", "52", "67.6", "87.88")]
[DataRow(1.5, "1.0", "60", "60", "60", "60")]
[DataRow(1.5, "1.3", "60", "78", "101.4", "131.82")]
[DataRow(4.0, "1.0", "120", "120", "120", "120")]
[DataRow(4.0, "1.3", "120", "156", "202.8", "263.64")]
public void TheDistanceScaleFollowsRvolAndTheGrowth(double rvol, string growth, string d1, string d2, string d3, string d4)
{
var g = decimal.Parse(growth, CultureInfo.InvariantCulture);
decimal[] expected = [.. new[] { d1, d2, d3, d4 }.Select(d => decimal.Parse(d, CultureInfo.InvariantCulture))];
for (var k = 1; k <= 4; k++)
{
Assert.AreEqual(expected[k - 1], BasketMath.Distance(40m, rvol, g, k), $"k = {k}");
}
CollectionAssert.AreEqual(expected, BasketMath.Distances(40m, rvol, g, maxReentries: 4).ToArray());
}
[TestMethod]
[TestCategory(Category.Unit)]
public void NoLevelIsAddedAfterTheLast()
{
// Three re-entries: four levels at most; the k-th addition is the one made with k levels open.
for (var levels = 1; levels <= 3; levels++)
{
Assert.IsTrue(BasketMath.CanAdd(levels, maxReentries: 3));
Assert.AreEqual(BasketMath.Distance(40m, 1.0, 1.3m, levels), BasketMath.NextDistance(levels, 3, 40m, 1.0, 1.3m));
}
Assert.IsFalse(BasketMath.CanAdd(4, maxReentries: 3));
Assert.IsNull(BasketMath.NextDistance(4, 3, 40m, 1.0, 1.3m));
Assert.IsFalse(BasketMath.ShouldAdd(-10_000m, levels: 4, maxReentries: 3, 40m, 1.0, 1.3m));
// With four re-entries (growth variant) the fifth level is the last.
Assert.IsTrue(BasketMath.CanAdd(4, maxReentries: 4));
Assert.IsFalse(BasketMath.CanAdd(5, maxReentries: 4));
Assert.IsFalse(BasketMath.CanAdd(0, maxReentries: 3));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ALevelIsAddedOnlyWhenTheLastLevelHasLostTheDistance()
{
// Second level (k = 1): 40 pips; third (k = 2) with growth 1.3: 52 pips, measured from the last level.
Assert.IsFalse(BasketMath.ShouldAdd(-39.9m, levels: 1, maxReentries: 3, 40m, 1.0, 1.3m));
Assert.IsTrue(BasketMath.ShouldAdd(-40m, levels: 1, maxReentries: 3, 40m, 1.0, 1.3m));
Assert.IsFalse(BasketMath.ShouldAdd(-51.9m, levels: 2, maxReentries: 3, 40m, 1.0, 1.3m));
Assert.IsTrue(BasketMath.ShouldAdd(-52m, levels: 2, maxReentries: 3, 40m, 1.0, 1.3m));
}
[TestMethod]
[TestCategory(Category.Unit)]
[DataRow("0.01", "40", -2310)]
[DataRow("0.02", "40", -1185)]
[DataRow("0.05", "40", -510)]
[DataRow("0.10", "40", -285)]
[DataRow("0.01", "65", -2348)]
[DataRow("0.02", "65", -1222)]
[DataRow("0.05", "65", -548)]
[DataRow("0.10", "65", -322)]
public void TheEightExcursionsOfTable412(string lot, string distance, int expected)
{
var l = decimal.Parse(lot, CultureInfo.InvariantCulture);
var d = decimal.Parse(distance, CultureInfo.InvariantCulture);
// Account 10,000 USD, stop at 9%, 10 USD per lot per pip, 1 + 3 levels; shown values rounded half to even.
var excursion = BasketMath.StopExcursion(4, d, l, 10m, 0.09m, 10_000m);
Assert.AreEqual((decimal)expected, Math.Round(excursion));
// At that excursion the pip sum loses exactly the 9%: 900 USD.
Assert.AreEqual(-900m, BasketMath.PipSumAtExcursion(4, excursion, d) * l * 10m);
}
[TestMethod]
[TestCategory(Category.Unit)]
[DataRow(500, -172)]
[DataRow(1000, -285)]
[DataRow(2500, -622)]
[DataRow(5000, -1185)]
[DataRow(10000, -2310)]
[DataRow(25000, -5685)]
public void TheCapitalTableOfSection69(int capital, int expected)
{
// Lot 0.01 (the pip sum is worth 0.1 USD), D = 40, four levels, 9% of capital.
Assert.AreEqual((decimal)expected, Math.Round(BasketMath.StopExcursion(4, 40m, 0.01m, 10m, 0.09m, capital)));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheLotForAGivenRiskInvertsTheExcursion()
{
// 0.09 × 10,000 / (10 × |4 × −285 + 6 × 40|) = 900 / 9,000 = 0.10.
Assert.AreEqual(0.10m, BasketMath.LotForRisk(4, -285m, 40m, 10m, 0.09m, 10_000m));
Assert.AreEqual(4 * -100m + (6 * 40m), BasketMath.PipSumAtExcursion(4, -100m, 40m));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ThePipValueOfAYenPairIsUnitsTimesPipOverUsdjpy()
{
// The ECB test day of the plan: USDJPY = 176.79 / 1.1193.
var usdjpy = 176.79m / 1.1193m;
var prices = Prices(("USDJPY", usdjpy));
Assert.AreEqual(1m / usdjpy, BasketMath.UsdPerUnit(Currencies.Jpy, prices));
AssertClose(10m / usdjpy, BasketMath.PipValue(FxPairs.Get("USDJPY"), 1000m, prices));
AssertClose(9.21m / usdjpy, BasketMath.PipValue(FxPairs.Get("EURJPY"), 921m, prices));
AssertClose(8.47m / usdjpy, BasketMath.PipValue(FxPairs.Get("CHFJPY"), 847m, prices));
AssertClose(0.0633124m, BasketMath.PipValue(FxPairs.Get("USDJPY"), 1000m, prices), 0.0000001m);
// Appendix A, units per 1,000 USD with USDJPY about 160.3: 0.062, 0.057 and 0.053 USD per pip.
var appendix = Prices(("USDJPY", 160.3m));
Assert.AreEqual(0.062m, Math.Round(BasketMath.PipValue(FxPairs.Get("USDJPY"), 1000m, appendix), 3));
Assert.AreEqual(0.057m, Math.Round(BasketMath.PipValue(FxPairs.Get("EURJPY"), 921m, appendix), 3));
Assert.AreEqual(0.053m, Math.Round(BasketMath.PipValue(FxPairs.Get("CHFJPY"), 847m, appendix), 3));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ThePipValueOfOtherQuotesUsesTheirDollarValue()
{
var prices = Prices(("EURUSD", 1.0856m), ("USDCHF", 0.847m), ("AUDUSD", 0.6623m));
Assert.AreEqual(1m, BasketMath.UsdPerUnit(Currencies.Usd, prices));
Assert.AreEqual(1.0856m, BasketMath.UsdPerUnit(Currencies.Eur, prices));
Assert.AreEqual(0.1m, BasketMath.PipValue(FxPairs.Get("EURUSD"), 1000m, prices));
Assert.AreEqual(0.1m / 0.847m, BasketMath.PipValue(FxPairs.Get("USDCHF"), 1000m, prices));
// Appendix A: 1,510 AUDUSD units per 1,000 USD are worth 0.151 USD per pip.
Assert.AreEqual(0.151m, BasketMath.PipValue(FxPairs.Get("AUDUSD"), 1510m, prices));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void BothLegsRiseToTheUnitsThatBringTheWeakestToTheVenueMinimum()
{
// 0.01 lot per 10,000 USD on 10,000 USD: 1,000 units, worth 662.3 USD on an AUD base, under the 1,000 USD minimum.
// 1,000 / 0.6623 = 1,509.89, rounded up: 1,510 on both legs (appendix A).
var aud = BasketMath.EqualUnits(0.01m, 10_000m, [1.0856m, 0.6623m]);
Assert.AreEqual(1510m, aud.Units);
Assert.IsTrue(aud.Raised);
Assert.AreEqual(0.0151m, aud.Lot());
// NZD base: 1,000 / 0.54172 = 1,845.97, rounded up: 1,846. (Appendix A rounds to the nearest unit: at exactly 0.5417
// the minimum needs 1,846.04, so 1,847 rounded up.)
var nzd = BasketMath.EqualUnits(0.01m, 10_000m, [0.6623m, 0.54172m]);
Assert.AreEqual(1846m, nzd.Units);
Assert.IsTrue(nzd.Units * 0.54172m >= 1000m);
Assert.AreEqual(1847m, BasketMath.EqualUnits(0.01m, 10_000m, [0.5417m]).Units);
// Above the minimum nothing moves: 2,000 units are 1,083 USD on the NZD leg.
var enough = BasketMath.EqualUnits(0.01m, 20_000m, [0.6623m, 0.54172m]);
Assert.AreEqual(2000m, enough.Units);
Assert.IsFalse(enough.Raised);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheNetExposureOfEqualUnitsOnEurusdAndUsdchf()
{
// Long 1,000 EURUSD at 1.0856: +1,000 EUR, −1,085.6 USD. Long 1,000 USDCHF at 0.847: +1,000 USD, −847 CHF.
var exposure = BasketMath.Exposure(
[
new ExposureLeg(FxPairs.Get("EURUSD"), Direction.Buy, 1000m, 1.0856m),
new ExposureLeg(FxPairs.Get("USDCHF"), Direction.Buy, 1000m, 0.847m),
]);
Assert.AreEqual(3, exposure.Count);
Assert.AreEqual(1000m, exposure[Currencies.Eur]);
Assert.AreEqual(-85.6m, exposure[Currencies.Usd]);
Assert.AreEqual(-86m, Math.Round(exposure[Currencies.Usd]));
Assert.AreEqual(-847m, exposure[Currencies.Chf]);
// Selling reverses every sign; in dollars the base is valued at its own price.
var sold = BasketMath.Exposure([new ExposureLeg(FxPairs.Get("EURUSD"), Direction.Sell, 1000m, 1.0856m)]);
Assert.AreEqual(-1000m, sold[Currencies.Eur]);
Assert.AreEqual(1085.6m, sold[Currencies.Usd]);
var dollars = BasketMath.UsdExposure(exposure, Prices(("EURUSD", 1.0856m), ("USDCHF", 0.847m)));
Assert.AreEqual(1085.6m, dollars[Currencies.Eur]);
AssertClose(-1000m, dollars[Currencies.Chf]);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheThreeCostsRulePassesThreeOfTheFiveDocumentedSpreads()
{
decimal[] costs = [2.1m, 2.5m, 6.9m, 2.9m, 4.7m];
var passing = costs.Where(c => BasketMath.PassesCostRule(10m, c)).ToArray();
CollectionAssert.AreEqual(new[] { 2.1m, 2.5m, 2.9m }, passing);
Assert.IsFalse(BasketMath.PassesCostRule(10m, 6.9m));
Assert.IsFalse(BasketMath.PassesCostRule(10m, 4.7m));
// Exactly three times the cost still passes.
Assert.IsTrue(BasketMath.PassesCostRule(9m, 3m));
Assert.IsFalse(BasketMath.PassesCostRule(8.99m, 3m));
}
private static Func<FxPair, decimal> Prices(params (string Pair, decimal Price)[] prices)
{
var map = prices.ToDictionary(p => p.Pair, p => p.Price, StringComparer.Ordinal);
return pair => map[pair.Name];
}
private static void AssertClose(decimal expected, decimal actual, decimal tolerance = 0.000000000001m) =>
Assert.IsTrue(Math.Abs(expected - actual) <= tolerance, $"{expected} ≠ {actual}");
}
+225
View File
@@ -0,0 +1,225 @@
using Anubis.Baskets;
namespace Anubis.Tests;
/// <summary>
/// The relations among the 28 pairs (Phase 12, issue #119): the counts of section 4.1, appendix B row by row, the eight
/// documented spreads of section 3.3, the sign of the index and the 14-pair list.
/// </summary>
[TestClass]
public sealed class BasketRelationTests
{
/// <summary>Appendix B, written out by hand from the document: row, leg A, leg B, synthetic cross.</summary>
private static readonly string[][] AppendixB =
[
["EURGBP", "GBPAUD", "EURAUD"], ["EURGBP", "GBPNZD", "EURNZD"], ["EURGBP", "GBPUSD", "EURUSD"],
["EURGBP", "GBPCAD", "EURCAD"], ["EURGBP", "GBPCHF", "EURCHF"], ["EURGBP", "GBPJPY", "EURJPY"],
["EURAUD", "AUDNZD", "EURNZD"], ["EURAUD", "AUDUSD", "EURUSD"], ["EURAUD", "AUDCAD", "EURCAD"],
["EURAUD", "AUDCHF", "EURCHF"], ["EURAUD", "AUDJPY", "EURJPY"], ["GBPAUD", "AUDNZD", "GBPNZD"],
["GBPAUD", "AUDUSD", "GBPUSD"], ["GBPAUD", "AUDCAD", "GBPCAD"], ["GBPAUD", "AUDCHF", "GBPCHF"],
["GBPAUD", "AUDJPY", "GBPJPY"], ["EURNZD", "NZDUSD", "EURUSD"], ["EURNZD", "NZDCAD", "EURCAD"],
["EURNZD", "NZDCHF", "EURCHF"], ["EURNZD", "NZDJPY", "EURJPY"], ["GBPNZD", "NZDUSD", "GBPUSD"],
["GBPNZD", "NZDCAD", "GBPCAD"], ["GBPNZD", "NZDCHF", "GBPCHF"], ["GBPNZD", "NZDJPY", "GBPJPY"],
["AUDNZD", "NZDUSD", "AUDUSD"], ["AUDNZD", "NZDCAD", "AUDCAD"], ["AUDNZD", "NZDCHF", "AUDCHF"],
["AUDNZD", "NZDJPY", "AUDJPY"], ["EURUSD", "USDCAD", "EURCAD"], ["EURUSD", "USDCHF", "EURCHF"],
["EURUSD", "USDJPY", "EURJPY"], ["GBPUSD", "USDCAD", "GBPCAD"], ["GBPUSD", "USDCHF", "GBPCHF"],
["GBPUSD", "USDJPY", "GBPJPY"], ["AUDUSD", "USDCAD", "AUDCAD"], ["AUDUSD", "USDCHF", "AUDCHF"],
["AUDUSD", "USDJPY", "AUDJPY"], ["NZDUSD", "USDCAD", "NZDCAD"], ["NZDUSD", "USDCHF", "NZDCHF"],
["NZDUSD", "USDJPY", "NZDJPY"], ["EURCAD", "CADCHF", "EURCHF"], ["EURCAD", "CADJPY", "EURJPY"],
["GBPCAD", "CADCHF", "GBPCHF"], ["GBPCAD", "CADJPY", "GBPJPY"], ["AUDCAD", "CADCHF", "AUDCHF"],
["AUDCAD", "CADJPY", "AUDJPY"], ["NZDCAD", "CADCHF", "NZDCHF"], ["NZDCAD", "CADJPY", "NZDJPY"],
["USDCAD", "CADCHF", "USDCHF"], ["USDCAD", "CADJPY", "USDJPY"], ["EURCHF", "CHFJPY", "EURJPY"],
["GBPCHF", "CHFJPY", "GBPJPY"], ["AUDCHF", "CHFJPY", "AUDJPY"], ["NZDCHF", "CHFJPY", "NZDJPY"],
["USDCHF", "CHFJPY", "USDJPY"], ["CADCHF", "CHFJPY", "CADJPY"],
];
[TestMethod]
[TestCategory(Category.Unit)]
public void TheCouplesOfTheTwentyEightPairsAre56Chains112RatiosAnd210Disjoint()
{
var couples = Relations.Couples;
Assert.AreEqual(378, couples.Count);
Assert.AreEqual(378, couples.Select(c => (c.A.Name, c.B.Name)).Distinct().Count());
Assert.AreEqual(56, couples.Count(c => c.Kind == RelationKind.Chain));
Assert.AreEqual(112, couples.Count(c => c.Kind == RelationKind.Ratio));
Assert.AreEqual(210, couples.Count(c => c.Kind == RelationKind.Disjoint));
// Every pair is the synthetic cross of exactly six couples that share a currency, one per other currency (section 4.1).
foreach (var pair in FxPairs.All)
{
Assert.AreEqual(6, couples.Count(c => c.Cross == pair), pair.Name);
}
Assert.IsTrue(couples.Where(c => c.Kind == RelationKind.Disjoint).All(c => c.Common is null && c.Cross is null));
Assert.IsTrue(couples.Where(c => c.Kind == RelationKind.Chain).All(c => !c.CrossInverted));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AppendixBIsReproducedRowByRow()
{
var rows = Relations.AppendixB;
int[] listed = [3, 9, 17, 29, 30, 35];
Assert.AreEqual(56, rows.Count);
for (var i = 0; i < AppendixB.Length; i++)
{
var row = rows[i];
var expected = AppendixB[i];
Assert.AreEqual(i + 1, row.Row);
Assert.AreEqual(expected[0], row.A.Name, $"riga {i + 1}");
Assert.AreEqual(expected[1], row.B.Name, $"riga {i + 1}");
Assert.AreEqual(expected[2], row.Cross.Name, $"riga {i + 1}");
Assert.AreEqual(listed.Contains(i + 1), row.Listed, $"riga {i + 1}");
// The common currency is the quote of A and the base of B; the classification agrees with the row.
Assert.AreEqual(row.A.Quote, row.B.Base);
var relation = Relations.Classify(row.A, row.B);
Assert.AreEqual(RelationKind.Chain, relation.Kind);
Assert.AreEqual(row.Cross, relation.Cross);
Assert.AreEqual(row.A.Quote, relation.Common);
}
// The 56 rows are the 56 chains of the 378 couples, each once.
var chains = Relations.Couples.Where(c => c.Kind == RelationKind.Chain).Select(c => Key(c.A, c.B)).ToHashSet();
CollectionAssert.AreEquivalent(chains.ToList(), rows.Select(r => Key(r.A, r.B)).ToList());
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheEightDocumentedSpreadsAreSixChainsAndTwoDisjointWhateverTheLegOrder()
{
(string A, string B, RelationKind Kind, string? Cross)[] expected =
[
("EURUSD", "USDCHF", RelationKind.Chain, "EURCHF"),
("AUDUSD", "USDCAD", RelationKind.Chain, "AUDCAD"),
("NZDUSD", "EURNZD", RelationKind.Chain, "EURUSD"),
("USDCAD", "EURUSD", RelationKind.Chain, "EURCAD"),
("EURAUD", "AUDCAD", RelationKind.Chain, "EURCAD"),
("GBPUSD", "EURGBP", RelationKind.Chain, "EURUSD"),
("NZDUSD", "AUDCHF", RelationKind.Disjoint, null),
("EURCHF", "AUDCAD", RelationKind.Disjoint, null),
];
var spreads = Relations.DocumentedSpreads;
Assert.AreEqual(8, spreads.Count);
for (var i = 0; i < expected.Length; i++)
{
var (a, b, kind, cross) = expected[i];
Assert.AreEqual(a, spreads[i].A.Name);
Assert.AreEqual(b, spreads[i].B.Name);
var forward = Relations.Classify(FxPairs.Get(a), FxPairs.Get(b));
var backward = Relations.Classify(FxPairs.Get(b), FxPairs.Get(a));
Assert.AreEqual(kind, forward.Kind, $"{a}–{b}");
Assert.AreEqual(kind, backward.Kind, $"{b}–{a}");
Assert.AreEqual(cross, forward.Cross?.Name, $"{a}–{b}");
Assert.AreEqual(cross, backward.Cross?.Name, $"{b}–{a}");
Assert.AreEqual(forward.Common, backward.Common);
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void NoClassificationDependsOnTheOrderOfTheLegs()
{
foreach (var couple in Relations.Couples)
{
var swapped = Relations.Classify(couple.B, couple.A);
Assert.AreEqual(couple.Kind, swapped.Kind);
Assert.AreEqual(couple.Cross, swapped.Cross);
Assert.AreEqual(couple.Common, swapped.Common);
// Only the orientation of a ratio's synthetic A/B turns over with the legs.
if (couple.Kind == RelationKind.Ratio)
{
Assert.AreNotEqual(couple.CrossInverted, swapped.CrossInverted);
}
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ARatioNamesItsSyntheticCrossAndWhetherItIsTheInverse()
{
// Both quote USD: EURUSD / GBPUSD = EURGBP (section 4.1); swapped it is 1/EURGBP.
var both = Relations.Classify(FxPairs.Get("EURUSD"), FxPairs.Get("GBPUSD"));
Assert.AreEqual(RelationKind.Ratio, both.Kind);
Assert.AreEqual("USD", both.Common);
Assert.AreEqual("EURGBP", both.Cross?.Name);
Assert.IsFalse(both.CrossInverted);
Assert.IsTrue(Relations.Classify(FxPairs.Get("GBPUSD"), FxPairs.Get("EURUSD")).CrossInverted);
// Both base EUR: EURUSD / EURGBP = USD per GBP = GBPUSD.
var bases = Relations.Classify(FxPairs.Get("EURUSD"), FxPairs.Get("EURGBP"));
Assert.AreEqual(RelationKind.Ratio, bases.Kind);
Assert.AreEqual("GBPUSD", bases.Cross?.Name);
Assert.IsFalse(bases.CrossInverted);
Assert.IsTrue(Relations.Classify(FxPairs.Get("EURGBP"), FxPairs.Get("EURUSD")).CrossInverted);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheSignIsPlusForChainsMinusForRatiosAndAgainstTheCorrelationForDisjoint()
{
Assert.AreEqual(1, Relations.Sign(RelationKind.Chain, null));
Assert.AreEqual(1, Relations.Sign(RelationKind.Chain, 0.9));
Assert.AreEqual(-1, Relations.Sign(RelationKind.Ratio, null));
Assert.AreEqual(-1, Relations.Sign(RelationKind.Ratio, -0.9));
Assert.AreEqual(-1, Relations.Sign(RelationKind.Disjoint, 0.3));
Assert.AreEqual(1, Relations.Sign(RelationKind.Disjoint, -0.3));
// With no correlation, or a zero one, a disjoint couple has no sign and cannot be traded.
Assert.IsNull(Relations.Sign(RelationKind.Disjoint, 0));
Assert.IsNull(Relations.Sign(RelationKind.Disjoint, null));
Assert.IsNull(Relations.Sign(RelationKind.Disjoint, double.NaN));
var disjoint = Relations.Classify(FxPairs.Get("NZDUSD"), FxPairs.Get("AUDCHF"));
Assert.AreEqual(-1, disjoint.Sign(0.5));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ACoupleOfAPairWithItselfIsRefused()
{
var pair = FxPairs.Get("EURUSD");
Assert.ThrowsExactly<ArgumentException>(() => Relations.Classify(pair, pair));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheFourteenPairListIsTheTwelveDocumentedSymbolsPlusEurcadAndAudnzd()
{
string[] expected =
[
"EURGBP", "EURAUD", "EURNZD", "EURUSD", "EURCAD", "EURCHF", "GBPUSD",
"AUDNZD", "AUDUSD", "AUDCAD", "AUDCHF", "NZDUSD", "USDCAD", "USDCHF",
];
var list = Relations.FourteenPairs;
CollectionAssert.AreEqual(expected, list.Select(p => p.Name).ToArray());
// Appendix A order, no yen: the order of the 28 with the others left out.
CollectionAssert.AreEqual(FxPairs.All.Where(list.Contains).ToArray(), list.ToArray());
Assert.IsFalse(list.Any(p => p.Quote == Currencies.Jpy));
// Every leg of the eight documented spreads is in the list.
Assert.IsTrue(Relations.DocumentedSpreads.All(s => list.Contains(s.A) && list.Contains(s.B)));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ThePipIsOneHundredthForYenPairsAndOneTenThousandthForTheOthers()
{
string[] yen = ["EURJPY", "GBPJPY", "AUDJPY", "NZDJPY", "USDJPY", "CADJPY", "CHFJPY"];
foreach (var pair in FxPairs.All)
{
Assert.AreEqual(yen.Contains(pair.Name) ? 0.01m : 0.0001m, pair.Pip, pair.Name);
}
Assert.AreEqual(7, FxPairs.All.Count(p => p.Pip == 0.01m));
}
private static string Key(FxPair a, FxPair b) => string.CompareOrdinal(a.Name, b.Name) < 0 ? a.Name + b.Name : b.Name + a.Name;
}
+322
View File
@@ -0,0 +1,322 @@
using System.Globalization;
using Anubis.Baskets;
namespace Anubis.Tests;
/// <summary>
/// The statistics of the basket maths (Phase 12, issue #119): the index in pips and in log basis points, z-score, Rvol with
/// its filter and factors, correlation, the hedge ratio, the states of a pair, the four styles, the two profiles, and the
/// rule that nothing computed at a closed bar looks at a later one.
/// </summary>
[TestClass]
public sealed class BasketSignalTests
{
[TestMethod]
[TestCategory(Category.Unit)]
public void ThePipIndexAddsTheLegsWithTheSignOfTheRelation()
{
var eurusd = FxPairs.Get("EURUSD");
var usdchf = FxPairs.Get("USDCHF");
// Chain, s = +1: 1.0856 / 0.0001 + 0.847 / 0.0001 = 10,856 + 8,470.
Assert.AreEqual(19_326, BasketIndex.Pips(1.0856, eurusd, 0.847, usdchf, +1), 1e-9);
Assert.AreEqual(2_386, BasketIndex.Pips(1.0856, eurusd, 0.847, usdchf, -1), 1e-9);
// Single symbol, and a yen pair with its 0.01 pip.
Assert.AreEqual(10_856, BasketIndex.Pips(1.0856, eurusd), 1e-9);
Assert.AreEqual(15_795, BasketIndex.Pips(157.95, FxPairs.Get("USDJPY")), 1e-9);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheLogIndexIsInBasisPoints()
{
// One basis point is 0.01%: a 1% rise of leg A is about 99.5 points.
Assert.AreEqual(10_000 * Math.Log(1.01), BasketIndex.LogBp(1.01, 1.0), 1e-9);
Assert.AreEqual(99.50330853168, BasketIndex.LogBp(1.01, 1.0), 1e-9);
Assert.AreEqual(10_000 * (Math.Log(50.0) - (1.5 * Math.Log(20.0))), BasketIndex.LogBp(50.0, 20.0, beta: 1.5), 1e-9);
Assert.AreEqual(10_000 * Math.Log(2.0), BasketIndex.LogBp(2.0), 1e-9);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheZScoreUsesTheSampleDeviationOfTheLastWValuesIncludingTheBar()
{
double[] index = [7, 1, 2, 3, 4, 10];
// Last 5 values ending at t = 5: 1, 2, 3, 4, 10. Mean 4; squares 9 + 4 + 1 + 0 + 36 = 50; sample variance 50 / 4
// = 12.5; deviation 5 / √2; z = (10 − 4) / (5 / √2) = 6√2 / 5 = 1.6970562748.
Assert.AreEqual(1.6970562748477141, BasketIndex.ZScore(index, 5, window: 5)!.Value, 1e-12);
// At t = 4 the window is 7, 1, 2, 3, 4: mean 3.4, squares 12.96 + 5.76 + 1.96 + 0.16 + 0.36 = 21.2, variance 5.3.
Assert.AreEqual((4 - 3.4) / Math.Sqrt(5.3), BasketIndex.ZScore(index, 4, window: 5)!.Value, 1e-12);
// Fewer than W values, a flat window or a missing value: no z.
Assert.IsNull(BasketIndex.ZScore(index, 3, window: 5));
Assert.IsNull(BasketIndex.ZScore([5, 5, 5, 5, 5], 4, window: 5));
Assert.IsNull(BasketIndex.ZScore([1, 2, double.NaN, 4, 5], 4, window: 5));
Assert.AreEqual(100, BasketIndex.DefaultWindow);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void RvolIsTheShortDeviationOverTheMedianOfItsBaseline()
{
// Index 0, 1, 3, 4, 6, 12: differences d1..d5 = 1, 2, 1, 2, 6. With 2 differences per short window the sample
// deviation of two values a, b is |a − b| / √2: σ(2) = σ(3) = σ(4) = 1 / √2, σ(5) = 4 / √2.
double[] index = [0, 1, 3, 4, 6, 12];
Assert.AreEqual(1 / Math.Sqrt(2), BasketIndex.ShortSigma(index, 2, shortBars: 2)!.Value, 1e-12);
Assert.AreEqual(4 / Math.Sqrt(2), BasketIndex.ShortSigma(index, 5, shortBars: 2)!.Value, 1e-12);
Assert.IsNull(BasketIndex.ShortSigma(index, 1, shortBars: 2));
// Baseline of 3: at t = 4 the median of σ(2), σ(3), σ(4) is 1 / √2, so Rvol = 1; at t = 5 the median of σ(3), σ(4),
// σ(5) is still 1 / √2, so Rvol = 4. At t = 3, σ(1) does not exist yet: no Rvol.
Assert.AreEqual(1.0, BasketIndex.Rvol(index, 4, baselineBars: 3, shortBars: 2)!.Value, 1e-12);
Assert.AreEqual(4.0, BasketIndex.Rvol(index, 5, baselineBars: 3, shortBars: 2)!.Value, 1e-12);
Assert.IsNull(BasketIndex.Rvol(index, 3, baselineBars: 3, shortBars: 2));
// A flat baseline has no Rvol.
Assert.IsNull(BasketIndex.Rvol([0, 1, 2, 3, 4, 5], 5, baselineBars: 3, shortBars: 2));
// An even baseline takes the mean of the two middle values: σ(4) and σ(5) → (1 + 4) / √2 / 2 against σ(5) = 4 / √2.
Assert.AreEqual(4.0 / 2.5, BasketIndex.Rvol(index, 5, baselineBars: 2, shortBars: 2)!.Value, 1e-12);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheDefaultRvolWindowsAreSixteenBarsAndTwentyDays()
{
Assert.AreEqual(16, BasketIndex.DefaultShortBars);
Assert.AreEqual(1920, BasketIndex.BaselineBars(barsPerDay: 96));
Assert.AreEqual(1920, BasketIndex.DefaultBaselineBars);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheVolatilityFilterBlocksNewEntriesAboveTwo()
{
Assert.IsTrue(BasketIndex.AllowsEntry(1.0));
Assert.IsTrue(BasketIndex.AllowsEntry(2.0));
Assert.IsFalse(BasketIndex.AllowsEntry(2.0001));
Assert.IsFalse(BasketIndex.AllowsEntry(4.0));
// Without enough history to know the volatility, no new entry.
Assert.IsFalse(BasketIndex.AllowsEntry(null));
Assert.IsFalse(BasketIndex.AllowsEntry(double.NaN));
}
[TestMethod]
[TestCategory(Category.Unit)]
[DataRow(0.5, "1", "0.7")]
[DataRow(0.8, "1", "0.8")]
[DataRow(1.0, "1", "1")]
[DataRow(1.5, "1.5", "1.5")]
[DataRow(3.0, "3", "3")]
[DataRow(4.0, "3", "3")]
public void TheRvolFactorsAreClampedAsTheDocumentSays(double rvol, string distance, string target)
{
Assert.AreEqual(decimal.Parse(distance, CultureInfo.InvariantCulture), BasketMath.DistanceFactor(rvol));
Assert.AreEqual(decimal.Parse(target, CultureInfo.InvariantCulture), BasketMath.TargetFactor(rvol));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheCorrelationIsPearsonOfLogReturnsOverTheWindow()
{
double[] a = [1.0, 1.1, 1.05, 1.2, 1.3];
var squared = a.Select(x => x * x).ToArray();
var inverse = a.Select(x => 1 / x).ToArray();
Assert.AreEqual(1.0, BasketIndex.Correlation(a, squared, 4, window: 4)!.Value, 1e-12);
Assert.AreEqual(-1.0, BasketIndex.Correlation(a, inverse, 4, window: 4)!.Value, 1e-12);
// Four returns need five prices; a flat leg has no correlation.
Assert.IsNull(BasketIndex.Correlation(a, squared, 3, window: 4));
Assert.IsNull(BasketIndex.Correlation(a, [2.0, 2.0, 2.0, 2.0, 2.0], 4, window: 4));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheHedgeRatioIsTheOlsSlopeOfLogPrices()
{
// ln A = ln 3 + 2 ln B exactly: β = 2.
double[] b = [1.0, 1.2, 0.9, 1.5, 1.1];
var a = b.Select(x => 3 * x * x).ToArray();
Assert.AreEqual(2.0, BasketIndex.HedgeRatio(a, b)!.Value, 1e-12);
Assert.IsNull(BasketIndex.HedgeRatio([1.0, 2.0], [3.0, 3.0]));
Assert.IsNull(BasketIndex.HedgeRatio([1.0], [3.0]));
}
[TestMethod]
[TestCategory(Category.Unit)]
[DataRow(0.0, true, false, PairState.Idle)]
[DataRow(1.49, true, false, PairState.Idle)]
[DataRow(1.5, true, false, PairState.Watch)]
[DataRow(-1.5, true, false, PairState.Watch)]
[DataRow(1.99, true, false, PairState.Watch)]
[DataRow(2.0, true, false, PairState.Open)]
[DataRow(-2.0, true, false, PairState.Open)]
[DataRow(2.0, false, false, PairState.Armed)]
[DataRow(-2.5, false, false, PairState.Armed)]
[DataRow(0.1, false, true, PairState.Open)]
public void ThePairStatesFollowTheThresholds(double z, bool gatesPass, bool open, PairState expected)
{
Assert.AreEqual(expected, PairStates.Of(z, entryZ: 2.0, gatesPass, hasOpenUnit: open));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void APairWithoutAZScoreIsIdle()
{
Assert.AreEqual(PairState.Idle, PairStates.Of(null, entryZ: 2.0, gatesPass: true));
Assert.AreEqual(1.5, PairStates.DefaultWatchZ);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheSignalBuysTheSpreadLowAndSellsItHighAndTheSpreadClosesNearZero()
{
Assert.AreEqual(Direction.Buy, PairStates.Signal(-2.0, entryZ: 2.0));
Assert.AreEqual(Direction.Sell, PairStates.Signal(2.0, entryZ: 2.0));
Assert.IsNull(PairStates.Signal(1.99, entryZ: 2.0));
Assert.IsNull(PairStates.Signal(null, entryZ: 2.0));
Assert.IsTrue(PairStates.SpreadClosed(0.5));
Assert.IsTrue(PairStates.SpreadClosed(-0.5));
Assert.IsFalse(PairStates.SpreadClosed(0.51));
Assert.IsFalse(PairStates.SpreadClosed(null));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheFourStylesCarryTheDocumentedValues()
{
(string Name, double EntryZ, int Spreads, int Averagings, int WithGrowth)[] expected =
[
("HedgeFund", 3.0, 1, 2, 2),
("Conservativo", 2.5, 2, 3, 3),
("Moderato", 2.0, 2, 3, 3),
("Aggressivo", 1.5, 3, 3, 4),
];
Assert.AreEqual(4, TradingStyles.All.Count);
for (var i = 0; i < expected.Length; i++)
{
var style = TradingStyles.All[i];
Assert.AreEqual(expected[i].Name, style.Name);
Assert.AreEqual(expected[i].EntryZ, style.EntryZ);
Assert.AreEqual(expected[i].Spreads, style.MaxOpenSpreads);
Assert.AreEqual(expected[i].Averagings, style.MaxAveragings);
Assert.AreEqual(expected[i].WithGrowth, style.MaxAveragingsWithGrowth);
}
Assert.AreSame(TradingStyles.Moderato, TradingStyles.Default);
Assert.AreSame(TradingStyles.Aggressivo, TradingStyles.Find("Aggressivo"));
Assert.IsNull(TradingStyles.Find("Spericolato"));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheTwoProfilesCarryTheDocumentedValues()
{
var fedele = BasketProfiles.Fedele;
Assert.AreEqual("Fedele", fedele.Name);
Assert.IsFalse(fedele.HasBasketStops());
Assert.AreEqual(0.09m, fedele.EquityStop);
Assert.IsTrue(fedele.ResumeAtNextServerDay);
Assert.IsFalse(fedele.CostGate);
Assert.IsNull(fedele.MaxCurrencyExposure);
Assert.IsTrue(fedele.OffRealAccountsOnly);
// The document's 1.5% basket loss is reduced to 1% by SPEC 9.2.
var prudente = BasketProfiles.Prudente;
Assert.AreEqual("Prudente", prudente.Name);
Assert.IsTrue(prudente.HasBasketStops());
Assert.AreEqual(3.5, prudente.StopZ);
Assert.AreEqual(0.01m, prudente.StopLoss);
Assert.IsTrue(prudente.StopOnBrokenRelation);
Assert.AreEqual(96, prudente.StopAfterBars);
Assert.IsTrue(prudente.CostGate);
Assert.AreEqual(2.0m, prudente.MaxCurrencyExposure);
Assert.AreEqual(0.09m, prudente.EquityStop);
Assert.IsTrue(prudente.ResumeAtNextServerDay);
Assert.IsFalse(prudente.OffRealAccountsOnly);
CollectionAssert.AreEqual(new[] { fedele, prudente }, BasketProfiles.All.ToArray());
}
[TestMethod]
[TestCategory(Category.Unit)]
public void NothingComputedAtABarDependsOnLaterBars()
{
var checkedValues = 0;
Property.ForAll(Walks, c =>
{
var past = c.Cut + 1;
var pastA = c.A[..past];
var pastB = c.B[..past];
var pastIndex = Index(pastA, pastB, c.Sign);
var fullIndex = Index(c.A, c.B, c.Sign);
var pastLog = pastA.Select((a, i) => BasketIndex.LogBp(a, pastB[i])).ToArray();
var fullLog = c.A.Select((a, i) => BasketIndex.LogBp(a, c.B[i])).ToArray();
Assert.AreEqual(pastIndex[c.Cut], fullIndex[c.Cut]);
Assert.AreEqual(pastLog[c.Cut], fullLog[c.Cut]);
var z = BasketIndex.ZScore(pastIndex, c.Cut, window: 20);
Assert.AreEqual(z, BasketIndex.ZScore(fullIndex, c.Cut, window: 20));
Assert.AreEqual(BasketIndex.ZScore(pastLog, c.Cut, window: 20), BasketIndex.ZScore(fullLog, c.Cut, window: 20));
var rvol = BasketIndex.Rvol(pastIndex, c.Cut, baselineBars: 12, shortBars: 4);
Assert.AreEqual(rvol, BasketIndex.Rvol(fullIndex, c.Cut, baselineBars: 12, shortBars: 4));
var rho = BasketIndex.Correlation(pastA, pastB, c.Cut, window: 20);
Assert.AreEqual(rho, BasketIndex.Correlation(c.A, c.B, c.Cut, window: 20));
var gates = BasketIndex.AllowsEntry(rvol) && rho is not null;
var pastState = PairStates.Of(z, entryZ: 2.0, gates, watchZ: 1.0);
var fullState = PairStates.Of(
BasketIndex.ZScore(fullIndex, c.Cut, window: 20),
entryZ: 2.0,
BasketIndex.AllowsEntry(BasketIndex.Rvol(fullIndex, c.Cut, baselineBars: 12, shortBars: 4))
&& BasketIndex.Correlation(c.A, c.B, c.Cut, window: 20) is not null,
watchZ: 1.0);
Assert.AreEqual(pastState, fullState);
if (z is not null && rvol is not null && rho is not null)
{
checkedValues++;
}
});
// The property is not empty: most cases have every statistic defined.
Assert.IsTrue(checkedValues > Property.DefaultCases / 2, checkedValues.ToString(CultureInfo.InvariantCulture));
}
private static double[] Index(double[] a, double[] b, int sign) =>
[.. a.Select((price, i) => BasketIndex.Pips(price, FxPairs.Get("EURUSD"), b[i], FxPairs.Get("USDCHF"), sign))];
private static Walk Walks(Gen gen)
{
var length = gen.Int(40, 120);
var future = gen.Int(1, 40);
var a = new double[length + future];
var b = new double[length + future];
a[0] = 1.1;
b[0] = 0.9;
for (var i = 1; i < a.Length; i++)
{
a[i] = a[i - 1] * Math.Exp(0.002 * gen.Normal());
b[i] = b[i - 1] * Math.Exp(0.002 * gen.Normal());
}
return new Walk(a, b, gen.Bool() ? 1 : -1, gen.Int(length / 2, length));
}
/// <summary>Two price walks; bars after <see cref="Cut"/> are the future that must not matter.</summary>
private sealed record Walk(double[] A, double[] B, int Sign, int Cut)
{
public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"{A.Length} barre, taglio {Cut}, segno {Sign}");
}
}
+162
View File
@@ -0,0 +1,162 @@
using System.Globalization;
using Anubis.Baskets;
using Anubis.Data;
namespace Anubis.Tests;
/// <summary>
/// The server clock of the research document (Phase 12, issue #119): New York time plus seven hours, the server day, the daily
/// pause, the hourly window and the weekend rule. Four dates cover winter, summer and the weeks in which the United States
/// and Europe change the clock on different days (2026: US 8 March and 1 November, Europe 29 March and 25 October).
/// </summary>
[TestClass]
public sealed class ServerClockTests
{
[TestMethod]
[TestCategory(Category.Unit)]
[DataRow("2026-01-15", 2, "2026-01-15T08:00:00Z", "2026-01-14T22:00:00Z")]
[DataRow("2026-03-16", 3, "2026-03-16T07:00:00Z", "2026-03-15T21:00:00Z")]
[DataRow("2026-07-15", 3, "2026-07-15T07:00:00Z", "2026-07-14T21:00:00Z")]
[DataRow("2026-10-27", 3, "2026-10-27T07:00:00Z", "2026-10-26T21:00:00Z")]
public void TheServerClockIsNewYorkPlusSevenHoursOnFourDates(string day, int offsetHours, string tenServerUtc, string midnightUtc)
{
var date = DateOnly.Parse(day, CultureInfo.InvariantCulture);
var ten = Utc(tenServerUtc);
var midnight = Utc(midnightUtc);
Assert.AreEqual(ten, ServerClock.At(date, new TimeOnly(10, 0)));
Assert.AreEqual(midnight, ServerClock.DayStart(date));
Assert.AreEqual(TimeSpan.FromHours(offsetHours), ServerClock.OffsetFromUtc(ten));
Assert.AreEqual(date.ToDateTime(new TimeOnly(10, 0)), ServerClock.ToServer(ten));
// The server day starts at server midnight, not a tick earlier.
Assert.AreEqual(date, ServerClock.Day(midnight));
Assert.AreEqual(date.AddDays(-1), ServerClock.Day(midnight.AddTicks(-1)));
Assert.AreEqual(date, ServerClock.Day(ten));
}
[TestMethod]
[TestCategory(Category.Unit)]
[DataRow("2026-01-15")]
[DataRow("2026-03-16")]
[DataRow("2026-07-15")]
[DataRow("2026-10-27")]
public void TheServerDayChangesAtFivePmNewYork(string day)
{
var date = DateOnly.Parse(day, CultureInfo.InvariantCulture);
var five = Zones.At(date, new TimeOnly(17, 0), Zones.NewYork);
Assert.AreEqual(date, ServerClock.Day(five.AddSeconds(-1)));
Assert.AreEqual(date.AddDays(1), ServerClock.Day(five));
Assert.AreEqual(ServerClock.DayStart(date.AddDays(1)), five);
}
[TestMethod]
[TestCategory(Category.Unit)]
[DataRow("2026-01-15", "2026-01-15T21:55:00Z", "2026-01-15T23:10:00Z")]
[DataRow("2026-03-16", "2026-03-16T20:55:00Z", "2026-03-16T22:10:00Z")]
[DataRow("2026-07-15", "2026-07-15T20:55:00Z", "2026-07-15T22:10:00Z")]
[DataRow("2026-10-27", "2026-10-27T20:55:00Z", "2026-10-27T22:10:00Z")]
public void TheDailyPauseRunsFrom1655To1810NewYorkHalfOpen(string day, string fromUtc, string toUtc)
{
var from = Utc(fromUtc);
var to = Utc(toUtc);
Assert.AreEqual(Zones.At(DateOnly.Parse(day, CultureInfo.InvariantCulture), new TimeOnly(16, 55), Zones.NewYork), from);
Assert.IsFalse(ServerClock.InDailyPause(from.AddSeconds(-1)));
Assert.IsTrue(ServerClock.InDailyPause(from));
Assert.IsTrue(ServerClock.InDailyPause(from.AddMinutes(30)));
Assert.IsTrue(ServerClock.InDailyPause(to.AddSeconds(-1)));
Assert.IsFalse(ServerClock.InDailyPause(to));
// The pause crosses server midnight; no entries inside it, whatever else allows them.
Assert.IsTrue(ServerClock.InDailyPause(ServerClock.DayStart(DateOnly.Parse(day, CultureInfo.InvariantCulture).AddDays(1))));
Assert.IsFalse(ServerClock.EntriesAllowed(from, sessionOn: false));
Assert.IsTrue(ServerClock.EntriesAllowed(to, sessionOn: false));
}
[TestMethod]
[TestCategory(Category.Unit)]
[DataRow("2026-01-16T14:00:00Z", "2026-01-19T00:00:00Z")]
[DataRow("2026-07-17T13:00:00Z", "2026-07-19T23:00:00Z")]
public void TheWeekendRuleBlocksFromFriday1600ToMonday0200ServerTimeHalfOpen(string fridayUtc, string mondayUtc)
{
var friday = Utc(fridayUtc);
var monday = Utc(mondayUtc);
Assert.AreEqual(DayOfWeek.Friday, ServerClock.ToServer(friday).DayOfWeek);
Assert.AreEqual(new TimeOnly(16, 0), TimeOnly.FromDateTime(ServerClock.ToServer(friday)));
Assert.AreEqual(DayOfWeek.Monday, ServerClock.ToServer(monday).DayOfWeek);
Assert.AreEqual(new TimeOnly(2, 0), TimeOnly.FromDateTime(ServerClock.ToServer(monday)));
Assert.IsFalse(ServerClock.InWeekend(friday.AddSeconds(-1)));
Assert.IsTrue(ServerClock.InWeekend(friday));
Assert.IsTrue(ServerClock.InWeekend(friday.AddDays(1)));
Assert.IsTrue(ServerClock.InWeekend(friday.AddDays(2)));
Assert.IsTrue(ServerClock.InWeekend(monday.AddSeconds(-1)));
Assert.IsFalse(ServerClock.InWeekend(monday));
Assert.IsFalse(ServerClock.InWeekend(monday.AddDays(3)));
Assert.IsFalse(ServerClock.EntriesAllowed(friday, sessionOn: false));
Assert.IsTrue(ServerClock.EntriesAllowed(monday, sessionOn: false));
}
[TestMethod]
[TestCategory(Category.Unit)]
[DataRow("2026-01-15")]
[DataRow("2026-03-16")]
[DataRow("2026-07-15")]
[DataRow("2026-10-27")]
public void TheHourlyWindowRunsFrom1000To2000ServerTimeHalfOpen(string day)
{
var date = DateOnly.Parse(day, CultureInfo.InvariantCulture);
var ten = ServerClock.At(date, new TimeOnly(10, 0));
var eight = ServerClock.At(date, new TimeOnly(20, 0));
Assert.IsFalse(ServerClock.InSession(ten.AddSeconds(-1)));
Assert.IsTrue(ServerClock.InSession(ten));
Assert.IsTrue(ServerClock.InSession(eight.AddSeconds(-1)));
Assert.IsFalse(ServerClock.InSession(eight));
// The window only matters when it is switched on.
Assert.IsFalse(ServerClock.EntriesAllowed(eight, sessionOn: true));
Assert.IsTrue(ServerClock.EntriesAllowed(eight, sessionOn: false));
Assert.IsTrue(ServerClock.EntriesAllowed(ten, sessionOn: true));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AfterTheEquityStopEntriesResumeAtTheNextServerDay()
{
// Thursday 15 January 2026, 15:00 New York = 22:00 server: the next server day starts at 17:00 New York.
var stop = new DateTimeOffset(2026, 1, 15, 20, 0, 0, TimeSpan.Zero);
Assert.AreEqual(new DateTimeOffset(2026, 1, 15, 22, 0, 0, TimeSpan.Zero), ServerClock.NextDayStart(stop));
// One minute after the change the next day is a whole day later.
var after = new DateTimeOffset(2026, 1, 15, 22, 1, 0, TimeSpan.Zero);
Assert.AreEqual(new DateTimeOffset(2026, 1, 16, 22, 0, 0, TimeSpan.Zero), ServerClock.NextDayStart(after));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void AServerTimeTurnsBackIntoTheSameMoment()
{
var gen = new Gen(Property.DefaultSeed);
var start = new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero);
for (var i = 0; i < 500; i++)
{
var moment = start.AddMinutes(gen.Int(0, 3 * 365 * 24 * 60));
var server = ServerClock.ToServer(moment);
// Away from the hour in which New York's clock goes back, a server time names one moment only.
if (server.DayOfWeek == DayOfWeek.Sunday && server.Hour is >= 7 and < 10)
{
continue;
}
Assert.AreEqual(moment, ServerClock.FromServer(server), moment.ToString("O", CultureInfo.InvariantCulture));
}
}
private static DateTimeOffset Utc(string text) =>
DateTimeOffset.Parse(text, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal);
}