From 47e08d6778cd7a4af2384c1a71daf2ee54a05e9d Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Fri, 4 Dec 2026 16:47:48 +0100 Subject: [PATCH] Add venue costs and the financing calendar for the basket engine The basket engine needs the costs and margin rules of the venue it simulates, dated and sourced, so a basket trial can copy them into its plan and its fingerprint changes when any value does. VenueCosts holds, per pair, the eToro values of the research document (appendix A and section 6.3, 1-2 December 2026): instrument id, real account leverage, bid/ask in normal hours and in the daily pause, commission per side (0.005%, 0.002% on USDJPY) and overnight financing in USD per 100,000 USD a night. The twelve legs of section 6.3 are stored as the document's pips x pip value per 1,000 USD x 100 (EURUSD buy 8.096, the 8.10 USD of section 6.7); the sixteen pairs without a rate pay the largest known charge on both sides and are marked estimated. Venue-wide: minimum 1,000 USD, default leverage 5, allowed leverages, mandatory stop at 50% of the margin, account liquidation at 50% of the initial margin. VenueCosts.None is the comparison configuration: no costs, no mandatory stop, no liquidation. Scaled(m) multiplies spread, pause spread, commission and financing charges only; credits stay. Margin, stop distance (none for a buy at leverage 1, as section 6.5 says) and a leverage check that refuses, in Italian, a leverage the venue or the pair does not allow. The JSON uses the plan's options and the fingerprint is its SHA-256. FinancingCalendar counts the rollovers at 17:00 New York (the server day change) on Monday to Friday, Wednesday triple, in closed form: a position held from Tuesday to Friday pays five nights. refs #128 Co-Authored-By: Claude Opus 5.5 --- src/Anubis/Backtest/VenueCosts.cs | 359 +++++++++++++++++++++ tests/Anubis.Tests/VenueCostsTests.cs | 434 ++++++++++++++++++++++++++ 2 files changed, 793 insertions(+) create mode 100644 src/Anubis/Backtest/VenueCosts.cs create mode 100644 tests/Anubis.Tests/VenueCostsTests.cs diff --git a/src/Anubis/Backtest/VenueCosts.cs b/src/Anubis/Backtest/VenueCosts.cs new file mode 100644 index 0000000..a066949 --- /dev/null +++ b/src/Anubis/Backtest/VenueCosts.cs @@ -0,0 +1,359 @@ +using System.Globalization; +using System.Text.Json; +using Anubis.Baskets; + +namespace Anubis.Backtest; + +/// +/// The costs of one pair at a venue (research document, appendix A and section 6.3). Spreads are in pips; the commission is +/// a fraction of the exposure paid on each side (0.00005 = 0.005%); financing is in USD per 100,000 USD of exposure per +/// night, positive a charge and negative a credit. marks a rate the document does not give: +/// the prudent stand-in is the largest known charge, on both sides. +/// +/// The market name: EURUSD. +/// The venue's instrument id, when known. +/// Bid/ask in pips in normal hours (appendix A, 23:03 UTC). +/// Bid/ask in pips inside the daily pause (appendix A, 22:31 UTC). +/// The real account's highest leverage on the pair. +/// Commission on each side, as a fraction of the exposure. +/// Overnight financing of a buy, USD per 100,000 USD per night. +/// Overnight financing of a sale, USD per 100,000 USD per night. +/// True when the financing is the prudent stand-in, not the document's rate. +public sealed record PairCost( + string Pair, + int? InstrumentId, + decimal Spread, + decimal PauseSpread, + int MaxLeverage, + decimal CommissionPerSide, + decimal FinancingBuy, + decimal FinancingSell, + bool FinancingEstimated) +{ + /// The pip of the pair: 0.01 when the quote is the yen, 0.0001 otherwise. + public decimal Pip() => FxPairs.Get(Pair).Pip; + + /// The bid/ask in pips, inside the daily pause or out of it. + public decimal SpreadPips(bool inPause) => inPause ? PauseSpread : Spread; + + /// The commission of one side in pips at a price: rate × price / pip (appendix A). + public decimal CommissionPips(decimal price) => CommissionPerSide * price / Pip(); + + /// The financing rate of a side, USD per 100,000 USD per night; positive is a charge. + public decimal FinancingRate(Direction side) => side == Direction.Buy ? FinancingBuy : FinancingSell; +} + +/// +/// The costs and margin rules of a venue, with their date and source, copied into the plan of a basket trial (plan, Phase 14, +/// point 2) so that a trial says which costs it ran with and its fingerprint changes with any of them. It serialises like +/// : snake_case, null fields left out. +/// +/// The venue: etoro, or none for the comparison configuration. +/// The day the values were read. +/// Where the values come from, in Italian: the report shows it. +/// The smallest exposure of a position, in USD (section 6.4). +/// The leverage per position when the plan names none (section 6.5). +/// The leverages the venue allows (section 6.4). +/// +/// The mandatory stop sits at most at this share of the position's margin (section 6.5); null when the venue imposes none. +/// +/// +/// Every position closes when the equity falls below this share of the initial margin of all open positions (section 6.10, +/// account-level); null when the venue has no such rule. +/// +/// The pairs, in the order of appendix A. +public sealed record VenueCosts( + string Venue, + DateOnly AsOf, + string Source, + decimal MinimumUsd, + int DefaultLeverage, + IReadOnlyList Leverages, + decimal? StopMarginShare, + decimal? LiquidationLevel, + IReadOnlyList Pairs) +{ + /// The exposure the financing rates are quoted on, in USD. + public const decimal FinancingExposure = 100_000m; + + /// + /// eToro on 1 and 2 December 2026 (research document, appendix A and section 6.3): the 28 pairs with id, real-account + /// leverage, the two bid/ask snapshots, 0.005% commission per side (0.002% on USDJPY, from the fee page) and the Demo + /// cost preview's overnight financing for the twelve legs of section 6.3. Those are stored in USD per 100,000 USD: + /// the document's pips per night × the pip value per 1,000 USD of appendix A × 100 (EURUSD buy 0.88 × 0.092 × 100 = + /// 8.096, the 8.10 USD of section 6.7). The other sixteen pairs pay, on both sides, the largest known charge (AUDCHF's + /// sale, 17.978) and are marked estimated. + /// + public static VenueCosts Etoro { get; } = BuildEtoro(); + + /// + /// The comparison configuration: the same pairs and leverages, no spread, commission or financing, no mandatory stop and + /// no liquidation. + /// + public static VenueCosts None { get; } = Etoro with + { + Venue = "none", + Source = "Configurazione di confronto: nessun costo, nessuno stop obbligatorio, nessuna chiusura d'ufficio.", + StopMarginShare = null, + LiquidationLevel = null, + Pairs = [.. Etoro.Pairs.Select(p => p with + { + InstrumentId = null, + Spread = 0m, + PauseSpread = 0m, + CommissionPerSide = 0m, + FinancingBuy = 0m, + FinancingSell = 0m, + FinancingEstimated = false, + })], + }; + + /// The costs of a pair, or null when the venue does not list it. + public PairCost? Find(string pair) => Pairs.FirstOrDefault(p => string.Equals(p.Pair, pair, StringComparison.Ordinal)); + + /// The costs of a pair; throws, in Italian, when the venue does not list it. + public PairCost Pair(string pair) => + Find(pair) ?? throw new ArgumentException($"{pair}: nessun costo per questa coppia nella tabella di {Venue}.", nameof(pair)); + + /// + /// The costs at times (SPEC 12.2, step 3): spread, pause spread, commission and the financing + /// charges grow; financing credits stay as they are, so a larger multiplier never pays more. 1 returns this instance. + /// + public VenueCosts Scaled(decimal multiplier) + { + ArgumentOutOfRangeException.ThrowIfNegative(multiplier); + if (multiplier == 1m) + { + return this; + } + + return this with + { + Pairs = [.. Pairs.Select(p => p with + { + Spread = p.Spread * multiplier, + PauseSpread = p.PauseSpread * multiplier, + CommissionPerSide = p.CommissionPerSide * multiplier, + FinancingBuy = Charge(p.FinancingBuy, multiplier), + FinancingSell = Charge(p.FinancingSell, multiplier), + })], + }; + } + + /// Refuses, in Italian, a leverage the venue does not allow or one above the pair's; returns it otherwise. + public int CheckLeverage(string pair, int leverage) + { + CheckLeverage(leverage); + var cost = Pair(pair); + if (leverage > cost.MaxLeverage) + { + throw new ArgumentException( + string.Create(CultureInfo.InvariantCulture, $"La leva {leverage} è oltre quella del conto reale su {pair}: al massimo {cost.MaxLeverage}."), + nameof(leverage)); + } + + return leverage; + } + + /// The margin of a position (appendix C): exposure / leverage, in the exposure's currency. + public decimal Margin(decimal exposureUsd, int leverage) + { + CheckLeverage(leverage); + return exposureUsd / leverage; + } + + /// + /// The farthest the mandatory stop can sit from the entry, in price units (section 6.5, appendix C): share of the margin / + /// leverage × price, so 0.5 / leverage × price. Null when the venue imposes no stop. + /// + public decimal? StopDistance(decimal price, int leverage) + { + CheckLeverage(leverage); + return StopMarginShare is { } share ? share / leverage * price : null; + } + + /// + /// The farthest stop of one position (section 6.5): the stop is required on every order above leverage 1 and on every + /// sale, so a buy at leverage 1 has none (null; the venue would let it go to 100% of the price, 95% on USDCHF). Refuses a + /// leverage above the pair's. + /// + public decimal? StopDistance(string pair, Direction side, decimal price, int leverage) + { + CheckLeverage(pair, leverage); + return side == Direction.Buy && leverage == 1 ? null : StopDistance(price, leverage); + } + + /// The farthest stop of one position in pips (table 6.5); null when there is none. + public decimal? StopDistancePips(string pair, Direction side, decimal price, int leverage) => + StopDistance(pair, side, price, leverage) is { } distance ? distance / Pair(pair).Pip() : null; + + /// The commission of one side on an exposure, in the exposure's currency. + public decimal Commission(string pair, decimal exposureUsd) => exposureUsd * Pair(pair).CommissionPerSide; + + /// + /// The overnight financing of a position over charged nights (): + /// exposure / 100,000 × rate × nights, in USD; positive is paid, negative received. + /// + public decimal Financing(string pair, Direction side, decimal exposureUsd, int nights) + { + ArgumentOutOfRangeException.ThrowIfNegative(nights); + return exposureUsd / FinancingExposure * Pair(pair).FinancingRate(side) * nights; + } + + /// The table as the plan stores it. + public string ToJson() => JsonSerializer.Serialize(this, TrialPlan.Json); + + public static VenueCosts FromJson(string text) => + JsonSerializer.Deserialize(text, TrialPlan.Json) ?? throw new JsonException("Tabella dei costi vuota"); + + /// SHA-256 of : any value changed changes it. + public string Fingerprint() => TrialPlan.Hash(ToJson()); + + /// Equal when every value is: the lists are compared item by item. + public bool Equals(VenueCosts? other) => + other is not null + && string.Equals(Venue, other.Venue, StringComparison.Ordinal) + && AsOf == other.AsOf + && string.Equals(Source, other.Source, StringComparison.Ordinal) + && MinimumUsd == other.MinimumUsd + && DefaultLeverage == other.DefaultLeverage + && Leverages.SequenceEqual(other.Leverages) + && StopMarginShare == other.StopMarginShare + && LiquidationLevel == other.LiquidationLevel + && Pairs.SequenceEqual(other.Pairs); + + public override int GetHashCode() => HashCode.Combine(Venue, AsOf, MinimumUsd, DefaultLeverage, StopMarginShare, LiquidationLevel, Pairs.Count); + + private void CheckLeverage(int leverage) + { + if (!Leverages.Contains(leverage)) + { + throw new ArgumentException( + string.Create(CultureInfo.InvariantCulture, $"La leva {leverage} non è ammessa su {Venue}: le leve possibili sono {string.Join(", ", Leverages)}."), + nameof(leverage)); + } + } + + private static decimal Charge(decimal rate, decimal multiplier) => rate > 0m ? rate * multiplier : rate; + + private static VenueCosts BuildEtoro() + { + // Section 6.3, USD per 100,000 USD per night (buy, sell): pips × pip value per 1,000 USD × 100. + var financing = new Dictionary(StringComparer.Ordinal) + { + ["EURUSD"] = (8.096m, -0.46m), // 0.88, −0.05 pip × 0.092 + ["USDCHF"] = (-7.788m, 15.458m), // −0.66, 1.31 × 0.118 + ["AUDUSD"] = (1.51m, 6.191m), // 0.10, 0.41 × 0.151 + ["USDCAD"] = (-0.77m, 8.33m), // −0.11, 1.19 × 0.070 + ["NZDUSD"] = (8.14m, 0.37m), // 0.44, 0.02 × 0.185 + ["EURNZD"] = (4.65m, 3.7m), // 0.93, 0.74 × 0.050 + ["EURAUD"] = (10.37m, -2.745m), // 1.70, −0.45 × 0.061 + ["AUDCAD"] = (-3.074m, 10.812m), // −0.29, 1.02 × 0.106 + ["GBPUSD"] = (3.927m, 3.696m), // 0.51, 0.48 × 0.077 + ["EURGBP"] = (7.92m, -0.36m), // 0.66, −0.03 × 0.120 + ["AUDCHF"] = (-10.324m, 17.978m), // −0.58, 1.01 × 0.178 + ["EURCHF"] = (-3.597m, 11.336m), // −0.33, 1.04 × 0.109 + }; + var largest = financing.Values.Max(f => Math.Max(f.Buy, f.Sell)); + + // Appendix A: pair, eToro id, real-account leverage, bid/ask at 23:03 UTC and at 22:31 UTC (in the pause), in pips. + (string Pair, int Id, int Leverage, decimal Spread, decimal Pause)[] rows = + [ + ("EURGBP", 8, 30, 0.4m, 2.3m), + ("EURAUD", 12, 20, 1.1m, 8.3m), + ("EURNZD", 49, 20, 4.3m, 16.8m), + ("EURUSD", 1, 30, 0.1m, 2.2m), + ("EURCAD", 13, 30, 0.9m, 8.4m), + ("EURCHF", 9, 30, 0.2m, 7.5m), + ("EURJPY", 10, 30, 1.6m, 11.2m), + ("GBPAUD", 50, 20, 1.2m, 14.9m), + ("GBPNZD", 52, 20, 8.3m, 25.0m), + ("GBPUSD", 2, 30, 0.2m, 2.3m), + ("GBPCAD", 65, 30, 2.0m, 11.0m), + ("GBPCHF", 51, 20, 1.0m, 23.3m), + ("GBPJPY", 11, 30, 0.9m, 14.8m), + ("AUDNZD", 48, 20, 0.8m, 6.9m), + ("AUDUSD", 7, 20, 0.1m, 2.1m), + ("AUDCAD", 47, 20, 1.0m, 7.1m), + ("AUDCHF", 46, 20, 0.9m, 13.5m), + ("AUDJPY", 14, 20, 0.7m, 7.0m), + ("NZDUSD", 3, 20, 0.1m, 2.8m), + ("NZDCAD", 53, 20, 1.6m, 7.3m), + ("NZDCHF", 54, 20, 1.0m, 12.2m), + ("NZDJPY", 55, 20, 1.6m, 9.8m), + ("USDCAD", 4, 30, 0.3m, 4.2m), + ("USDCHF", 6, 30, 0.1m, 11.2m), + ("USDJPY", 5, 30, 0.3m, 5.8m), + ("CADCHF", 56, 30, 0.8m, 11.6m), + ("CADJPY", 15, 30, 0.8m, 10.7m), + ("CHFJPY", 16, 30, 1.7m, 58.4m), + ]; + + var pairs = rows.Select(r => + { + var known = financing.TryGetValue(r.Pair, out var rate); + return new PairCost( + r.Pair, + r.Id, + r.Spread, + r.Pause, + r.Leverage, + r.Pair == "USDJPY" ? 0.00002m : 0.00005m, + known ? rate.Buy : largest, + known ? rate.Sell : largest, + !known); + }).ToArray(); + + return new VenueCosts( + "etoro", + new DateOnly(2026, 12, 2), + "Documento di ricerca, appendice A e sezione 6.3: anteprime dei costi del conto Demo e pagina delle commissioni di eToro, 1 e 2 dicembre 2026", + BasketMath.VenueMinimumUsd, + 5, + [1, 2, 5, 10, 20, 30], + 0.5m, + 0.5m, + pairs); + } +} + +/// +/// The nights a position pays financing for (section 6.3, «il mercoledì conta triplo»): one rollover at every server day +/// change, 17:00 New York (), whose New York weekday is Monday to Friday; Wednesday's counts three +/// and there is none on Saturday and Sunday, seven a week. A position opened on a Tuesday before 17:00 and closed on the +/// Friday before 17:00 crosses Tuesday's, Wednesday's and Thursday's: five nights. +/// +public static class FinancingCalendar +{ + /// The nights charged by the rollover at 17:00 New York of a New York day: 3 on Wednesday, 0 on the weekend, 1 otherwise. + public static int Units(DateOnly newYorkDay) => newYorkDay.DayOfWeek switch + { + DayOfWeek.Saturday or DayOfWeek.Sunday => 0, + DayOfWeek.Wednesday => 3, + _ => 1, + }; + + /// The moment of a New York day's rollover: 17:00 New York, the start of the next server day. + public static DateTimeOffset Rollover(DateOnly newYorkDay) => ServerClock.DayStart(newYorkDay.AddDays(1)); + + /// The nights of the rollovers r with < r ≤ ; 0 when to is not after from. + public static int Nights(DateTimeOffset from, DateTimeOffset to) + { + if (to <= from) + { + return 0; + } + + // The rollover of New York day d starts server day d + 1, so from < r ≤ to exactly when Day(from) ≤ d < Day(to). + var first = ServerClock.Day(from); + var days = ServerClock.Day(to).DayNumber - first.DayNumber; + var weeks = days / 7; + var nights = weeks * 7; + for (var day = first.AddDays(weeks * 7); day.DayNumber < first.DayNumber + days; day = day.AddDays(1)) + { + nights += Units(day); + } + + return nights; + } +} diff --git a/tests/Anubis.Tests/VenueCostsTests.cs b/tests/Anubis.Tests/VenueCostsTests.cs new file mode 100644 index 0000000..0ed2898 --- /dev/null +++ b/tests/Anubis.Tests/VenueCostsTests.cs @@ -0,0 +1,434 @@ +using System.Globalization; +using Anubis.Backtest; +using Anubis.Baskets; +using Anubis.Data; + +namespace Anubis.Tests; + +/// +/// The costs of a venue for the basket engine (Phase 14, issue #128): the eToro table copied from appendix A and section 6.3 +/// of the research document, margin and mandatory stop of tables 6.4 and 6.5, the financing calendar with the triple +/// Wednesday, the 2× and 3× cost multipliers and the fingerprint the plan carries. Every expected number is the document's, +/// or worked out by hand in the comment next to it. +/// +[TestClass] +public sealed class VenueCostsTests +{ + // Appendix A, one row per pair in its order: eToro id, real-account leverage, bid/ask at 23:03 UTC and at 22:31 UTC (in + // the pause), commission per side in pips, units per 1,000 USD, pip value per 1,000 USD. + private static readonly (string Pair, int Id, int Leverage, decimal Spread, decimal Pause, decimal CommissionPips, int Units, decimal PipValue)[] AppendixA = + [ + ("EURGBP", 8, 30, 0.4m, 2.3m, 0.42m, 921, 0.120m), + ("EURAUD", 12, 20, 1.1m, 8.3m, 0.82m, 921, 0.061m), + ("EURNZD", 49, 20, 4.3m, 16.8m, 1.00m, 921, 0.050m), + ("EURUSD", 1, 30, 0.1m, 2.2m, 0.54m, 921, 0.092m), + ("EURCAD", 13, 30, 0.9m, 8.4m, 0.77m, 921, 0.065m), + ("EURCHF", 9, 30, 0.2m, 7.5m, 0.46m, 921, 0.109m), + ("EURJPY", 10, 30, 1.6m, 11.2m, 0.87m, 921, 0.057m), + ("GBPAUD", 50, 20, 1.2m, 14.9m, 0.98m, 768, 0.051m), + ("GBPNZD", 52, 20, 8.3m, 25.0m, 1.20m, 768, 0.042m), + ("GBPUSD", 2, 30, 0.2m, 2.3m, 0.65m, 768, 0.077m), + ("GBPCAD", 65, 30, 2.0m, 11.0m, 0.93m, 768, 0.054m), + ("GBPCHF", 51, 20, 1.0m, 23.3m, 0.55m, 768, 0.091m), + ("GBPJPY", 11, 30, 0.9m, 14.8m, 1.05m, 768, 0.048m), + ("AUDNZD", 48, 20, 0.8m, 6.9m, 0.61m, 1510, 0.082m), + ("AUDUSD", 7, 20, 0.1m, 2.1m, 0.33m, 1510, 0.151m), + ("AUDCAD", 47, 20, 1.0m, 7.1m, 0.47m, 1510, 0.106m), + ("AUDCHF", 46, 20, 0.9m, 13.5m, 0.28m, 1510, 0.178m), + ("AUDJPY", 14, 20, 0.7m, 7.0m, 0.53m, 1510, 0.094m), + ("NZDUSD", 3, 20, 0.1m, 2.8m, 0.27m, 1846, 0.185m), + ("NZDCAD", 53, 20, 1.6m, 7.3m, 0.39m, 1846, 0.129m), + ("NZDCHF", 54, 20, 1.0m, 12.2m, 0.23m, 1846, 0.218m), + ("NZDJPY", 55, 20, 1.6m, 9.8m, 0.44m, 1846, 0.115m), + ("USDCAD", 4, 30, 0.3m, 4.2m, 0.71m, 1000, 0.070m), + ("USDCHF", 6, 30, 0.1m, 11.2m, 0.42m, 1000, 0.118m), + ("USDJPY", 5, 30, 0.3m, 5.8m, 0.32m, 1000, 0.062m), + ("CADCHF", 56, 30, 0.8m, 11.6m, 0.30m, 1427, 0.169m), + ("CADJPY", 15, 30, 0.8m, 10.7m, 0.56m, 1427, 0.089m), + ("CHFJPY", 16, 30, 1.7m, 58.4m, 0.95m, 847, 0.053m), + ]; + + // Section 6.3: overnight financing of the twelve legs the table names, in pips per night (buy, sell); positive is a charge. + private static readonly (string Pair, decimal Buy, decimal Sell)[] FinancingPips = + [ + ("EURUSD", 0.88m, -0.05m), + ("USDCHF", -0.66m, 1.31m), + ("AUDUSD", 0.10m, 0.41m), + ("USDCAD", -0.11m, 1.19m), + ("NZDUSD", 0.44m, 0.02m), + ("EURNZD", 0.93m, 0.74m), + ("EURAUD", 1.70m, -0.45m), + ("AUDCAD", -0.29m, 1.02m), + ("GBPUSD", 0.51m, 0.48m), + ("EURGBP", 0.66m, -0.03m), + ("AUDCHF", -0.58m, 1.01m), + ("EURCHF", -0.33m, 1.04m), + ]; + + // Table 6.5, maximum stop distance in pips at leverage 30, 20, 10, 5, 2 (null: the leverage is above the pair's), with the + // 1 December price every cell of the row implies: the one four-decimal price at which all five cells round to the table. + private static readonly (string Pair, decimal Price, int?[] Pips)[] Table65 = + [ + ("EURUSD", 1.0859m, [181, 271, 543, 1086, 2715]), + ("USDCHF", 0.8472m, [141, 212, 424, 847, 2118]), + ("AUDUSD", 0.6621m, [null, 166, 331, 662, 1655]), + ("USDCAD", 1.4272m, [238, 357, 714, 1427, 3568]), + ("NZDUSD", 0.5416m, [null, 135, 271, 542, 1354]), + ("EURNZD", 2.0044m, [null, 501, 1002, 2004, 5011]), + ("EURAUD", 1.6400m, [null, 410, 820, 1640, 4100]), + ("AUDCAD", 0.9452m, [null, 236, 473, 945, 2363]), + ("GBPUSD", 1.3016m, [217, 325, 651, 1302, 3254]), + ("EURGBP", 0.8344m, [139, 209, 417, 834, 2086]), + ("AUDCHF", 0.5608m, [null, 140, 280, 561, 1402]), + ("EURCHF", 0.9196m, [153, 230, 460, 920, 2299]), + ]; + + private static readonly int[] Table65Leverages = [30, 20, 10, 5, 2]; + + [TestMethod] + [TestCategory(Category.Unit)] + public void MarginAndMandatoryStopFollowTables64And65() + { + var costs = VenueCosts.Etoro; + + // Table 6.4 at 1,000 USD of exposure: margin, the loss at the 50% stop, 8 and 16 positions of a two-leg basket, 5 of a + // single trade. The loss at the stop is the exposure times the stop distance over the price: 1,000 × 0.5 / leverage. + (int Leverage, string Margin, string Loss, int Eight, int Sixteen, int Five)[] table64 = + [ + (30, "33.33", "16.67", 267, 533, 167), + (20, "50.00", "25.00", 400, 800, 250), + (10, "100.00", "50.00", 800, 1600, 500), + (5, "200.00", "100.00", 1600, 3200, 1000), + (2, "500.00", "250.00", 4000, 8000, 2500), + ]; + foreach (var row in table64) + { + var margin = costs.Margin(1_000m, row.Leverage); + Assert.AreEqual(row.Margin, Round(margin, 2), $"margine a leva {row.Leverage}"); + var distance = costs.StopDistance(1.0859m, row.Leverage); + Assert.IsNotNull(distance); + Assert.AreEqual(row.Loss, Round(1_000m * distance.Value / 1.0859m, 2), $"perdita allo stop a leva {row.Leverage}"); + Assert.AreEqual(row.Loss, Round(margin * costs.StopMarginShare!.Value, 2)); + Assert.AreEqual(row.Eight, (int)Math.Round(8 * margin, MidpointRounding.AwayFromZero)); + Assert.AreEqual(row.Sixteen, (int)Math.Round(16 * margin, MidpointRounding.AwayFromZero)); + Assert.AreEqual(row.Five, (int)Math.Round(5 * margin, MidpointRounding.AwayFromZero)); + } + + // Leverage 1: 1,000 USD of margin; a buy needs no stop and can lose all of it, a short sale keeps the 50% rule. + Assert.AreEqual(1_000m, costs.Margin(1_000m, 1)); + Assert.AreEqual(8_000m, 8 * costs.Margin(1_000m, 1)); + Assert.AreEqual(16_000m, 16 * costs.Margin(1_000m, 1)); + Assert.AreEqual(5_000m, 5 * costs.Margin(1_000m, 1)); + Assert.IsNull(costs.StopDistance("EURUSD", Direction.Buy, 1.0859m, 1)); + Assert.AreEqual(0.54295m, costs.StopDistance("EURUSD", Direction.Sell, 1.0859m, 1)); + + // Table 6.5: every cell from the implied price, both sides; the cells marked «non disponibile» are refused. + foreach (var (pair, price, cells) in Table65) + { + for (var i = 0; i < Table65Leverages.Length; i++) + { + var leverage = Table65Leverages[i]; + if (cells[i] is not { } expected) + { + Assert.ThrowsExactly(() => costs.StopDistancePips(pair, Direction.Sell, price, leverage), $"{pair} a leva {leverage}"); + continue; + } + + foreach (var side in new[] { Direction.Buy, Direction.Sell }) + { + var pips = costs.StopDistancePips(pair, side, price, leverage); + Assert.IsNotNull(pips); + Assert.AreEqual(expected, (int)Math.Round(pips.Value, MidpointRounding.AwayFromZero), $"{pair} {side} a leva {leverage}"); + } + } + } + + // The default choice of section 6.5: leverage 5, stop at about 10% of the price, 0.5 / 5 × 1.0859 = 0.10859. + Assert.AreEqual(5, costs.DefaultLeverage); + Assert.AreEqual(0.10859m, costs.StopDistance(1.0859m, 5)); + Assert.AreEqual(0.10859m, costs.StopDistance("EURUSD", Direction.Buy, 1.0859m, 5)); + + // The comparison venue has no mandatory stop. + Assert.IsNull(VenueCosts.None.StopDistance(1.0859m, 5)); + Assert.IsNull(VenueCosts.None.StopDistancePips("EURUSD", Direction.Sell, 1.0859m, 5)); + Assert.IsNull(VenueCosts.None.LiquidationLevel); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void APositionOpenedTuesdayAndClosedFridayPaysFiveNights() + { + // Tuesday 1 December 2026 to Friday 4 December, 10:00 New York: rollovers on Tuesday (1), Wednesday (3) and Thursday (1). + Assert.AreEqual(5, FinancingCalendar.Nights(NewYork("2026-12-01", 10), NewYork("2026-12-04", 10))); + + // The ECB bar moments: open on Tuesday's bar (00:00 UTC), close on Friday's: the same three rollovers. + Assert.AreEqual(5, FinancingCalendar.Nights(Utc("2026-12-01T00:00:00Z"), Utc("2026-12-04T00:00:00Z"))); + + // In summer too (New York on daylight time): Tuesday 7 July to Friday 10 July 2026. + Assert.AreEqual(5, FinancingCalendar.Nights(NewYork("2026-07-07", 9), NewYork("2026-07-10", 16))); + Assert.AreEqual(5, FinancingCalendar.Nights(Utc("2026-07-07T00:00:00Z"), Utc("2026-07-10T00:00:00Z"))); + + // The rollover is the server day change, 17:00 New York: a position opened at that very moment does not pay Tuesday's, + // one closed at Friday's pays it. + Assert.AreEqual(5, FinancingCalendar.Nights(NewYork("2026-12-01", 16, 59), NewYork("2026-12-04", 16, 59))); + Assert.AreEqual(4, FinancingCalendar.Nights(NewYork("2026-12-01", 17), NewYork("2026-12-04", 10))); + Assert.AreEqual(6, FinancingCalendar.Nights(NewYork("2026-12-01", 10), NewYork("2026-12-04", 17))); + + // Wednesday alone counts three; Friday one; none on Saturday and Sunday; a whole week seven; nothing backwards. + Assert.AreEqual(3, FinancingCalendar.Nights(NewYork("2026-12-02", 16), NewYork("2026-12-02", 18))); + Assert.AreEqual(1, FinancingCalendar.Nights(NewYork("2026-12-04", 12), NewYork("2026-12-07", 12))); + Assert.AreEqual(0, FinancingCalendar.Nights(NewYork("2026-12-05", 12), NewYork("2026-12-06", 18))); + Assert.AreEqual(7, FinancingCalendar.Nights(NewYork("2026-11-30", 12), NewYork("2026-12-07", 12))); + Assert.AreEqual(0, FinancingCalendar.Nights(NewYork("2026-12-04", 12), NewYork("2026-12-01", 12))); + + // Over the whole ECB history the closed form equals counting every 17:00 New York, day by day. + var from = Utc("1999-01-04T00:00:00Z"); + var to = Utc("2026-12-02T00:00:00Z"); + var counted = 0; + for (var day = new DateOnly(1999, 1, 1); day <= new DateOnly(2026, 12, 3); day = day.AddDays(1)) + { + var rollover = Zones.At(day, new TimeOnly(17, 0), Zones.NewYork); + if (rollover > from && rollover <= to && day.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday)) + { + counted += day.DayOfWeek == DayOfWeek.Wednesday ? 3 : 1; + } + } + + Assert.AreEqual(counted, FinancingCalendar.Nights(from, to)); + + // The charge: 1,000 USD of EURUSD bought for five nights at 8.096 USD per 100,000 a night = 0.4048 USD; sold, a credit + // of 0.46 per 100,000 a night = −0.023. + Assert.AreEqual(0.4048m, VenueCosts.Etoro.Financing("EURUSD", Direction.Buy, 1_000m, 5)); + Assert.AreEqual(-0.023m, VenueCosts.Etoro.Financing("EURUSD", Direction.Sell, 1_000m, 5)); + Assert.AreEqual(0m, VenueCosts.Etoro.Financing("EURUSD", Direction.Buy, 1_000m, 0)); + Assert.AreEqual(0m, VenueCosts.None.Financing("EURUSD", Direction.Buy, 1_000m, 5)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void CostMultipliersScaleCommissionSpreadAndPaidFinancingOnly() + { + var one = VenueCosts.Etoro; + Assert.AreEqual(one, one.Scaled(1m)); + Assert.AreEqual(one.Fingerprint(), one.Scaled(1m).Fingerprint()); + + foreach (var m in new[] { 2m, 3m }) + { + var scaled = one.Scaled(m); + Assert.AreEqual(one.Venue, scaled.Venue); + Assert.AreEqual(one.AsOf, scaled.AsOf); + Assert.AreEqual(one.MinimumUsd, scaled.MinimumUsd); + Assert.AreEqual(one.DefaultLeverage, scaled.DefaultLeverage); + Assert.AreEqual(one.StopMarginShare, scaled.StopMarginShare); + Assert.AreEqual(one.LiquidationLevel, scaled.LiquidationLevel); + CollectionAssert.AreEqual(one.Leverages.ToArray(), scaled.Leverages.ToArray()); + Assert.AreNotEqual(one.Fingerprint(), scaled.Fingerprint()); + Assert.AreEqual(one.Pairs.Count, scaled.Pairs.Count); + + for (var i = 0; i < one.Pairs.Count; i++) + { + var a = one.Pairs[i]; + var b = scaled.Pairs[i]; + Assert.AreEqual(a.Pair, b.Pair); + Assert.AreEqual(a.InstrumentId, b.InstrumentId); + Assert.AreEqual(a.MaxLeverage, b.MaxLeverage); + Assert.AreEqual(a.FinancingEstimated, b.FinancingEstimated); + Assert.AreEqual(a.Spread * m, b.Spread, a.Pair); + Assert.AreEqual(a.PauseSpread * m, b.PauseSpread, a.Pair); + Assert.AreEqual(a.CommissionPerSide * m, b.CommissionPerSide, a.Pair); + + // A charge grows with the multiplier; a credit stays what it is. + Assert.AreEqual(a.FinancingBuy > 0m ? a.FinancingBuy * m : a.FinancingBuy, b.FinancingBuy, a.Pair); + Assert.AreEqual(a.FinancingSell > 0m ? a.FinancingSell * m : a.FinancingSell, b.FinancingSell, a.Pair); + } + + // EURUSD at 3×: spread 0.3, commission 0.015%, buy financing 24.288; the sell credit stays −0.46. + if (m == 3m) + { + var eurusd = scaled.Pair("EURUSD"); + Assert.AreEqual(0.3m, eurusd.Spread); + Assert.AreEqual(0.00015m, eurusd.CommissionPerSide); + Assert.AreEqual(24.288m, eurusd.FinancingBuy); + Assert.AreEqual(-0.46m, eurusd.FinancingSell); + Assert.AreEqual(3m * one.Financing("EURUSD", Direction.Buy, 5_000m, 5), scaled.Financing("EURUSD", Direction.Buy, 5_000m, 5)); + Assert.AreEqual(one.Financing("EURUSD", Direction.Sell, 5_000m, 5), scaled.Financing("EURUSD", Direction.Sell, 5_000m, 5)); + } + } + + // Costs that are zero stay zero; a negative multiplier means nothing. + Assert.AreEqual(VenueCosts.None, VenueCosts.None.Scaled(3m)); + Assert.AreEqual(VenueCosts.None.Fingerprint(), VenueCosts.None.Scaled(3m).Fingerprint()); + Assert.ThrowsExactly(() => one.Scaled(-1m)); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheEtoroTableCopiesAppendixA() + { + var costs = VenueCosts.Etoro; + Assert.AreEqual("etoro", costs.Venue); + Assert.AreEqual(new DateOnly(2026, 12, 2), costs.AsOf); + StringAssert.Contains(costs.Source, "appendice A"); + StringAssert.Contains(costs.Source, "sezione 6.3"); + Assert.AreEqual(1_000m, costs.MinimumUsd); + Assert.AreEqual(5, costs.DefaultLeverage); + Assert.AreEqual(0.5m, costs.StopMarginShare); + Assert.AreEqual(0.5m, costs.LiquidationLevel); + CollectionAssert.AreEqual(new[] { 1, 2, 5, 10, 20, 30 }, costs.Leverages.ToArray()); + + // The 28 pairs in the order of appendix A, which is the order of FxPairs.All. + CollectionAssert.AreEqual(FxPairs.All.Select(p => p.Name).ToArray(), costs.Pairs.Select(p => p.Pair).ToArray()); + CollectionAssert.AreEqual(AppendixA.Select(r => r.Pair).ToArray(), costs.Pairs.Select(p => p.Pair).ToArray()); + Assert.AreEqual(34.0m, costs.Pairs.Sum(p => p.Spread)); + Assert.AreEqual(318.6m, costs.Pairs.Sum(p => p.PauseSpread)); + Assert.AreEqual(14, costs.Pairs.Count(p => p.MaxLeverage == 30)); + Assert.AreEqual(14, costs.Pairs.Count(p => p.MaxLeverage == 20)); + + // The 1 December prices appendix A implies: usd(c) = 1,000 / units of a pair with base c; the yen from USDJPY's pip value. + var usd = new Dictionary(StringComparer.Ordinal) + { + [Currencies.Usd] = 1m, + [Currencies.Jpy] = 0.062m / (1_000m * 0.01m), + }; + foreach (var row in AppendixA) + { + usd.TryAdd(row.Pair[..3], 1_000m / row.Units); + } + + foreach (var row in AppendixA) + { + var cost = costs.Pair(row.Pair); + Assert.AreEqual(row.Id, cost.InstrumentId, row.Pair); + Assert.AreEqual(row.Leverage, cost.MaxLeverage, row.Pair); + Assert.AreEqual(row.Spread, cost.Spread, row.Pair); + Assert.AreEqual(row.Pause, cost.PauseSpread, row.Pair); + Assert.AreEqual(row.Pair == "USDJPY" ? 0.00002m : 0.00005m, cost.CommissionPerSide, row.Pair); + + var price = usd[row.Pair[..3]] / usd[row.Pair[3..]]; + var pips = cost.CommissionPips(price); + Assert.IsTrue(Math.Abs(pips - row.CommissionPips) <= 0.01m, $"{row.Pair}: {pips.ToString("0.000", CultureInfo.InvariantCulture)} pip contro {row.CommissionPips}"); + } + + // USDJPY at 0.005% would be 0.81 pip, not the 0.32 of the table: the fee page's 0.002% is the one that fits. + var usdjpy = usd[Currencies.Usd] / usd[Currencies.Jpy]; + Assert.IsTrue(Math.Abs((0.00005m * usdjpy / 0.01m) - 0.32m) > 0.4m); + + // Financing: the twelve legs of section 6.3, stored in USD per 100,000 USD a night (pips × pip value per 1,000 × 100), + // give back the document's pips exactly; EURUSD's buy is the 8.10 USD of section 6.7. + foreach (var (pair, buy, sell) in FinancingPips) + { + var cost = costs.Pair(pair); + var pipValue = AppendixA.Single(r => r.Pair == pair).PipValue; + Assert.IsFalse(cost.FinancingEstimated, pair); + Assert.AreEqual(buy, cost.FinancingBuy / (pipValue * 100m), pair); + Assert.AreEqual(sell, cost.FinancingSell / (pipValue * 100m), pair); + } + + Assert.AreEqual(8.10m, Math.Round(costs.Pair("EURUSD").FinancingBuy, 2)); + + // The sixteen pairs the document gives no rate for pay, on both sides, the largest known charge: AUDCHF's sale. + var largest = FinancingPips.SelectMany(f => new[] { costs.Pair(f.Pair).FinancingBuy, costs.Pair(f.Pair).FinancingSell }).Max(); + Assert.AreEqual(costs.Pair("AUDCHF").FinancingSell, largest); + Assert.AreEqual(17.978m, largest); + var estimated = costs.Pairs.Where(p => p.FinancingEstimated).ToArray(); + Assert.AreEqual(16, estimated.Length); + Assert.IsTrue(estimated.All(p => p.FinancingBuy == largest && p.FinancingSell == largest)); + Assert.IsTrue(estimated.All(p => FinancingPips.All(f => f.Pair != p.Pair))); + + // The comparison venue: the same pairs and leverages, nothing to pay. + var none = VenueCosts.None; + Assert.AreEqual(28, none.Pairs.Count); + Assert.IsTrue(none.Pairs.All(p => p is { Spread: 0m, PauseSpread: 0m, CommissionPerSide: 0m, FinancingBuy: 0m, FinancingSell: 0m, FinancingEstimated: false })); + Assert.IsNull(none.StopMarginShare); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void AnUnknownLeverageIsRefusedInItalian() + { + var costs = VenueCosts.Etoro; + foreach (var leverage in new[] { 0, 3, 50, 400 }) + { + var error = Assert.ThrowsExactly(() => costs.Margin(1_000m, leverage)); + StringAssert.Contains(error.Message, "leva"); + StringAssert.Contains(error.Message, "1, 2, 5, 10, 20, 30"); + Assert.ThrowsExactly(() => costs.StopDistance(1.0859m, leverage)); + } + + // Above the pair's real-account leverage: AUDUSD stops at 20, GBPCHF too (less than the European 30). + var tooHigh = Assert.ThrowsExactly(() => costs.CheckLeverage("AUDUSD", 30)); + StringAssert.Contains(tooHigh.Message, "AUDUSD"); + StringAssert.Contains(tooHigh.Message, "20"); + Assert.ThrowsExactly(() => costs.CheckLeverage("GBPCHF", 30)); + Assert.ThrowsExactly(() => costs.StopDistance("GBPCHF", Direction.Buy, 1.1m, 30)); + Assert.AreEqual(30, costs.CheckLeverage("EURUSD", 30)); + Assert.AreEqual(20, costs.CheckLeverage("AUDUSD", 20)); + + // A pair that is not in the table. + var unknown = Assert.ThrowsExactly(() => costs.Pair("EURSEK")); + StringAssert.Contains(unknown.Message, "EURSEK"); + StringAssert.Contains(unknown.Message, "coppia"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheFingerprintChangesWithAnyValue() + { + var costs = VenueCosts.Etoro; + var print = costs.Fingerprint(); + Assert.AreEqual(64, print.Length); + Assert.IsTrue(print.All(c => c is >= '0' and <= '9' or >= 'a' and <= 'f')); + + // Written like the plan: snake_case, null fields left out; read back it is the same table with the same fingerprint. + var json = costs.ToJson(); + StringAssert.Contains(json, "\"commission_per_side\":"); + StringAssert.Contains(json, "\"financing_estimated\":"); + StringAssert.Contains(json, "\"as_of\":\"2026-12-02\""); + var back = VenueCosts.FromJson(json); + Assert.AreEqual(costs, back); + Assert.AreEqual(print, back.Fingerprint()); + Assert.AreEqual(json, back.ToJson()); + Assert.IsFalse(VenueCosts.None.ToJson().Contains("stop_margin_share", StringComparison.Ordinal)); + Assert.IsFalse(VenueCosts.None.ToJson().Contains("liquidation_level", StringComparison.Ordinal)); + Assert.AreNotEqual(print, VenueCosts.None.Fingerprint()); + + var eurusd = costs.Pair("EURUSD"); + VenueCosts WithPair(PairCost changed) => costs with { Pairs = [.. costs.Pairs.Select(p => p.Pair == changed.Pair ? changed : p)] }; + VenueCosts[] changes = + [ + costs with { Venue = "altra" }, + costs with { AsOf = costs.AsOf.AddDays(1) }, + costs with { Source = costs.Source + "." }, + costs with { MinimumUsd = 999m }, + costs with { DefaultLeverage = 2 }, + costs with { Leverages = [1, 2, 5, 10, 20] }, + costs with { StopMarginShare = 0.4m }, + costs with { StopMarginShare = null }, + costs with { LiquidationLevel = 0.3m }, + costs with { Pairs = [.. costs.Pairs.Take(27)] }, + WithPair(eurusd with { InstrumentId = 99 }), + WithPair(eurusd with { InstrumentId = null }), + WithPair(eurusd with { Spread = 0.2m }), + WithPair(eurusd with { PauseSpread = 2.3m }), + WithPair(eurusd with { MaxLeverage = 20 }), + WithPair(eurusd with { CommissionPerSide = 0.00006m }), + WithPair(eurusd with { FinancingBuy = 8.097m }), + WithPair(eurusd with { FinancingSell = -0.47m }), + WithPair(eurusd with { FinancingEstimated = true }), + ]; + + var prints = new HashSet(StringComparer.Ordinal) { print }; + foreach (var changed in changes) + { + Assert.AreNotEqual(costs, changed); + Assert.IsTrue(prints.Add(changed.Fingerprint()), changed.ToJson()); + } + } + + private static string Round(decimal value, int decimals) => Math.Round(value, decimals, MidpointRounding.AwayFromZero).ToString("F" + decimals, CultureInfo.InvariantCulture); + + private static DateTimeOffset Utc(string text) => DateTimeOffset.Parse(text, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); + + private static DateTimeOffset NewYork(string day, int hour, int minute = 0) => + Zones.At(DateOnly.Parse(day, CultureInfo.InvariantCulture), new TimeOnly(hour, minute), Zones.NewYork); +}