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>
This commit is contained in:
1 parent
3bee136c74
commit
a8defde572
15 files changed
+488
-143
No files matched your search
@@ -157,6 +157,85 @@ public sealed class BasketCommandTests
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task AnInterruptedBasketTrialIsRecordedAsFailedWithAnItalianReason()
|
||||
{
|
||||
// Ctrl+C or the stop of the container while the trial runs: the command's token is cancelled as soon as it says the
|
||||
// trial is planned. The trial is recorded as failed with a reason the user can act on, no report is written, exit 1.
|
||||
var (env, postgres) = await ServerHarness.DockerOnEngineAsync().ConfigureAwait(false);
|
||||
await using var engine = postgres;
|
||||
var data = TempFolder.Create("baskets-stop");
|
||||
var clock = new ManualClock(new DateTimeOffset(2026, 12, 4, 9, 0, 0, TimeSpan.Zero));
|
||||
try
|
||||
{
|
||||
var config = ServerOptions.Parse(["--platform", "docker", "--data-dir", data], env).LoadConfig(env);
|
||||
await using var db = Database.Open(config.Db!);
|
||||
await Migrations.MigrateAsync(db, clock, null, CancellationToken.None).ConfigureAwait(false);
|
||||
Directory.CreateDirectory(config.Data.Research);
|
||||
await File.WriteAllBytesAsync(Ecb.HistoryPath(config.Data.Research), EcbZip()).ConfigureAwait(false);
|
||||
var outDir = Path.Combine(data, "out");
|
||||
|
||||
using var stop = new CancellationTokenSource();
|
||||
using var output = new StopOnLine(stop, "Prova ");
|
||||
var code = await BasketCommand.RunAsync(
|
||||
["--offline", "--to", "2001-12-31", "--control", "1", "--out", outDir, "--platform", "docker", "--data-dir", data], output, env, new FakeHttp(), clock,
|
||||
stop.Token).ConfigureAwait(false);
|
||||
|
||||
const string Interrupted = "Prova interrotta prima della fine: rilancia «anubis backtest baskets».";
|
||||
Assert.AreEqual(1, code, output.ToString());
|
||||
StringAssert.Contains(output.ToString(), "Non riuscito: " + Interrupted);
|
||||
Assert.IsFalse(output.ToString().Contains(" at ", StringComparison.Ordinal), "no stack trace");
|
||||
var trial = (await new TrialStore(db, clock).ListAsync(10, CancellationToken.None).ConfigureAwait(false)).Single();
|
||||
Assert.AreEqual(TrialStatuses.Failed, trial.Status);
|
||||
Assert.AreEqual(Interrupted, trial.Error);
|
||||
Assert.IsFalse(File.Exists(Path.Combine(outDir, BasketReport.Strategy + ".md")), "an interrupted trial writes no report");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
|
||||
TempFolder.Delete(data);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheLaboratoryFailsALeftoverBasketTrialWithAnAccurateReason()
|
||||
{
|
||||
// A basket trial left planned or running by a command that died is picked up by the laboratory at the next start. The
|
||||
// family only runs from the command line: the trial fails with a reason that says so, not «no longer available».
|
||||
var clock = new ManualClock(new DateTimeOffset(2026, 12, 4, 9, 0, 0, TimeSpan.Zero));
|
||||
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
||||
using var lab = new Laboratory(test.Db, clock, Path.GetTempPath());
|
||||
var (plan, variants) = BasketProtocol.Plan(To, clock.UtcNow);
|
||||
var left = await lab.Trials.PlanAsync(plan, variants, CancellationToken.None).ConfigureAwait(false);
|
||||
|
||||
await lab.ProcessAsync(left.Id, CancellationToken.None).ConfigureAwait(false);
|
||||
|
||||
var failed = (await lab.Trials.GetAsync(left.Id, CancellationToken.None).ConfigureAwait(false))!;
|
||||
Assert.AreEqual(TrialStatuses.Failed, failed.Status);
|
||||
Assert.AreEqual("Prova a panieri interrotta: si rilancia da riga di comando con «anubis backtest baskets».", failed.Error);
|
||||
}
|
||||
|
||||
/// <summary>Console output that cancels the command's token at the first line starting with <c>start</c>.</summary>
|
||||
private sealed class StopOnLine(CancellationTokenSource stop, string start) : StringWriter(System.Globalization.CultureInfo.InvariantCulture)
|
||||
{
|
||||
public override void WriteLine(string? value)
|
||||
{
|
||||
base.WriteLine(value);
|
||||
if (value is not null && value.StartsWith(start, StringComparison.Ordinal))
|
||||
{
|
||||
stop.Cancel();
|
||||
}
|
||||
}
|
||||
|
||||
public override Task WriteLineAsync(string? value)
|
||||
{
|
||||
WriteLine(value);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A trigger that changes every plan as soon as it is written: someone touching the register behind the command.</summary>
|
||||
private static async Task TamperAsync(Database db, string set)
|
||||
{
|
||||
|
||||
@@ -341,6 +341,95 @@ public sealed class BasketEngineTests
|
||||
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()
|
||||
|
||||
@@ -127,29 +127,54 @@ public sealed class BasketReportTests
|
||||
new("EURUSD-USDCHF", opened.AddDays(3), opened.AddDays(4), 1_000m, 2, ["EURUSD", "USDCHF"], "orphan_leg", -12m),
|
||||
new("AUDNZD", opened.AddDays(5), opened.AddDays(9), 1_000m, 1, ["AUDNZD"], "target", 9m),
|
||||
new("AUDNZD", opened.AddDays(10), opened.AddDays(12), 1_000m, 1, ["AUDNZD"], "target", 8m),
|
||||
new("GBPUSD", opened.AddDays(20), null, 1_000m, 1, ["GBPUSD"], null, -3m),
|
||||
new("GBPUSD", opened.AddDays(20), null, 1_000m, 1, ["GBPUSD"], BasketReasons.End, -3m),
|
||||
];
|
||||
var notes = new Dictionary<string, int>(StringComparer.Ordinal)
|
||||
{
|
||||
["orphan_leg"] = 2,
|
||||
["closed_with_stop"] = 3,
|
||||
["gate_open_loss"] = 5,
|
||||
["weird_code"] = 1,
|
||||
};
|
||||
var two = Section(BasketReport.Markdown(Input(trial with { Report = trial.Report with { Notes = notes, Baskets = baskets } })), "## Prova del motore a panieri");
|
||||
StringAssert.Contains(two, "Gambe rimaste sole: 2");
|
||||
StringAssert.Contains(two, "Posizioni chiuse insieme a un livello fermato dallo stop obbligatorio: 3 (");
|
||||
StringAssert.Contains(two, "| stop obbligatorio della piattaforma | 1 |");
|
||||
StringAssert.Contains(two, "| gamba rimasta sola dopo uno stop obbligatorio | 1 |");
|
||||
StringAssert.Contains(two, "| obiettivo raggiunto | 2 |");
|
||||
StringAssert.Contains(two, "| ancora aperto alla fine | 1 |");
|
||||
StringAssert.Contains(two, "| ancora aperto alla fine (valutato agli ultimi prezzi) | 1 |");
|
||||
StringAssert.Contains(two, "Panieri della variante giudicata: 5.");
|
||||
StringAssert.Contains(two, "perdita aperta oltre il 2%");
|
||||
StringAssert.Contains(two, "| perdita aperta pari o oltre il 2%: nessun paniere nuovo | 5 |");
|
||||
StringAssert.Contains(two, "| `weird_code` | 1 |");
|
||||
StringAssert.Contains(two, "Chiusi all'obiettivo: 50,0%");
|
||||
Assert.IsFalse(two.Contains("`closed_with_stop`", StringComparison.Ordinal), "closes, not refusals");
|
||||
Assert.IsFalse(two.Contains("fine del periodo", StringComparison.Ordinal), "a basket open at the end was not closed");
|
||||
|
||||
// Two at the target out of the four closed: the one still open at the end is not counted among the closed.
|
||||
StringAssert.Contains(two, "Chiusi all'obiettivo: 50,0% dei panieri chiusi");
|
||||
|
||||
var none = Section(BasketReport.Markdown(Input(trial with { Report = trial.Report with { Notes = new Dictionary<string, int>(), Baskets = [] } })), "## Prova del motore a panieri");
|
||||
StringAssert.Contains(none, "Gambe rimaste sole: 0");
|
||||
StringAssert.Contains(none, "Chiusure d'ufficio per margine insufficiente: 0");
|
||||
StringAssert.Contains(none, "Stop sul valore del conto: 0");
|
||||
StringAssert.Contains(none, "Posizioni chiuse insieme a un livello fermato dallo stop obbligatorio: 0 (");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheLimitsAreWrittenOnce()
|
||||
{
|
||||
// With a trial, the engine's own limitations already speak of the ECB prices and of the costs: the report does not
|
||||
// repeat its own version of them. Without one, it writes them.
|
||||
const string Prices = "- I prezzi sono i cambi di riferimento della BCE, uno al giorno";
|
||||
const string Costs = "- I costi sono quelli di eToro letti il 02/12/2026";
|
||||
var withTrial = Section(BasketReport.Markdown(Input(_trial.Value)), "## Cosa il backtest non rappresenta");
|
||||
var without = Section(BasketReport.Markdown(Input(null, "Nessuna prova.")), "## Cosa il backtest non rappresenta");
|
||||
|
||||
StringAssert.Contains(withTrial, "- Motore finto della prova.");
|
||||
Assert.AreEqual(0, Count(withTrial, Prices), withTrial);
|
||||
Assert.AreEqual(0, Count(withTrial, Costs), withTrial);
|
||||
Assert.AreEqual(1, Count(without, Prices), without);
|
||||
Assert.AreEqual(1, Count(without, Costs), without);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -174,14 +199,33 @@ public sealed class BasketReportTests
|
||||
[BasketReasons.RvolFilter] = 1,
|
||||
[BasketReasons.CorrelationLow] = 1,
|
||||
[BasketReasons.SwitchTripped] = 1,
|
||||
[BasketReasons.MaxOpenBaskets] = 1,
|
||||
[BasketReasons.MaxOpenBaskets] = 1_569,
|
||||
};
|
||||
var text = Section(BasketReport.Markdown(Input(trial with { Report = trial.Report with { Notes = notes } })), "## Prova del motore a panieri");
|
||||
StringAssert.Contains(text, "| troppe posizioni aperte per la piattaforma | 3 |");
|
||||
var report = trial.Report with
|
||||
{
|
||||
Notes = notes,
|
||||
LookAhead = trial.Report.LookAhead with { Decisions = 4_817 },
|
||||
Overfitting = new ReportOverfitting(16, 12_870, 4, 0.25),
|
||||
};
|
||||
var text = Section(BasketReport.Markdown(Input(trial with { Report = report })), "## Prova del motore a panieri");
|
||||
|
||||
// Each label says what the engine does (BasketSimulation, ReasonCatalog).
|
||||
StringAssert.Contains(text, "| si supererebbero 9 posizioni aperte (conto Demo condiviso) | 3 |");
|
||||
StringAssert.Contains(text, "| fuori dalla finestra oraria | 4 |");
|
||||
StringAssert.Contains(text, "| perdita aperta pari o oltre il 2%: nessun paniere nuovo | 1 |");
|
||||
StringAssert.Contains(text, "| volatilità recente oltre il doppio del normale, o non ancora nota | 1 |");
|
||||
StringAssert.Contains(text, "| perdita del giorno pari o oltre il 2%: niente ingressi né mediazioni per 24 ore | 1 |");
|
||||
StringAssert.Contains(text, "| correlazione tra le gambe sotto 0,6 sul segno atteso, o non ancora nota | 1 |");
|
||||
StringAssert.Contains(text, "| esposizione netta su una valuta oltre due ingressi (solo panieri nuovi) | 1 |");
|
||||
StringAssert.Contains(text, "| dimensione ridotta a metà o a un quarto (perdita della settimana o calo dal massimo) | 1 |");
|
||||
StringAssert.Contains(text, "Posizioni chiuse dallo stop obbligatorio della piattaforma: 6.");
|
||||
var refusals = text[text.IndexOf("**Ingressi e mediazioni fermati o annotati**", StringComparison.Ordinal)..];
|
||||
Assert.IsFalse(refusals.Contains('`', StringComparison.Ordinal), "a code without a label: " + refusals);
|
||||
|
||||
// Counts are grouped the Italian way, like every other number of the report.
|
||||
StringAssert.Contains(text, "| già aperto il numero massimo di panieri | 1.569 |");
|
||||
StringAssert.Contains(text, "4.817 decisioni");
|
||||
StringAssert.Contains(text, "su 12.870 combinazioni");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
@@ -193,7 +237,9 @@ public sealed class BasketReportTests
|
||||
StringAssert.Contains(text, "zero (nessuna operazione)");
|
||||
Assert.IsFalse(text.Contains("comprare e tenere", StringComparison.OrdinalIgnoreCase));
|
||||
Assert.IsFalse(text.Contains("buy and hold", StringComparison.OrdinalIgnoreCase));
|
||||
StringAssert.Contains(text, "**Sensibilità ai costi** (commissione, differenziale e finanziamento pagato moltiplicati insieme)");
|
||||
StringAssert.Contains(text, "**Sensibilità ai costi** (differenziale, commissioni e finanziamento a carico moltiplicati insieme; gli accrediti di finanziamento restano uguali)");
|
||||
StringAssert.Contains(text, "| Commissioni e finanziamento pagati (il differenziale è già nei prezzi) | ");
|
||||
Assert.IsFalse(text.Contains("| Costi pagati |", StringComparison.Ordinal));
|
||||
StringAssert.Contains(text, "| ×2 |");
|
||||
StringAssert.Contains(text, "| ×3 |");
|
||||
}
|
||||
|
||||
@@ -189,6 +189,42 @@ public sealed class BasketTrialEngineTests
|
||||
Assert.AreEqual(engine.Sessions, surrogate.Run(StrategyParameters.Of(BasketReversionFamily.Instance, "generation=2;signal=2;units=2;target=2.5;distance=4;exit=2")).Equity.Count);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void WithBidAndAskTheSurrogateKeepsTheSizeOfEveryMidChange()
|
||||
{
|
||||
// 15-minute EURUSD quotes two pips wide around a walking mid, from Tuesday 13 January 2026 20:00 UTC over four server
|
||||
// days whose signs alternate. The engine reads the mid: in the surrogate every change of the mid keeps its size and
|
||||
// the spread stays around it. Chained on the bid, the mid would jump by a whole spread at each change of sign.
|
||||
var first = new DateTimeOffset(2026, 1, 13, 20, 0, 0, TimeSpan.Zero);
|
||||
var walk = BasketSynthetic.Walk(200, 7, 0, 0.0004);
|
||||
var data = BasketSynthetic.Quarters(first, new Dictionary<string, (QuoteSide, QuoteSide)[]>
|
||||
{
|
||||
["EURUSD"] = [.. walk.Select(x => BasketSynthetic.Mid(Math.Round(1.1m * (decimal)Math.Exp(x), 5), 0.0002m))],
|
||||
});
|
||||
var market = BasketMarket.Of(data);
|
||||
var days = market.Day(market.Count - 1).DayNumber - market.Day(0).DayNumber + 1;
|
||||
Assert.IsTrue(days >= 3, $"{days} server days");
|
||||
var signs = new DaySigns(market.Day(0), [.. Enumerable.Range(0, days).Select(i => i % 2 == 0 ? 1 : -1)]);
|
||||
|
||||
var surrogate = market.Surrogate(signs, centred: false);
|
||||
|
||||
var before = market.Reference("EURUSD");
|
||||
var after = surrogate.Reference("EURUSD");
|
||||
var (bid, ask) = (surrogate.Bid("EURUSD").Close, surrogate.Ask("EURUSD")!.Close);
|
||||
var (bid0, ask0) = (market.Bid("EURUSD").Close, market.Ask("EURUSD")!.Close);
|
||||
var turned = 0;
|
||||
for (var t = 1; t < before.Count; t++)
|
||||
{
|
||||
Assert.AreEqual(Math.Abs(Math.Log(before[t] / before[t - 1])), Math.Abs(Math.Log(after[t] / after[t - 1])), 1e-7, $"bar {t}");
|
||||
Assert.IsTrue(bid[t] < ask[t], $"bar {t}");
|
||||
Assert.AreEqual((ask0[t] - bid0[t]) / before[t], (ask[t] - bid[t]) / after[t], 1e-6, $"bar {t}: the spread stays around the mid");
|
||||
turned += market.Day(t) != market.Day(t - 1) ? 1 : 0;
|
||||
}
|
||||
|
||||
Assert.IsTrue(turned >= 2, $"{turned} changes of sign");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheFamilyHasOneIdForEverySubVariant()
|
||||
|
||||
@@ -65,8 +65,11 @@ public sealed class VenueCostsTests
|
||||
("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.
|
||||
// Table 6.5, maximum stop distance in pips at leverage 30, 20, 10, 5, 2 (null: the leverage is above the pair's), with a
|
||||
// four-decimal price worked back from the table, at which all five cells of the row round to the document's values. It is
|
||||
// not an independent 1 December price and not the only one that fits (each row has two to four such prices, e.g. EURUSD
|
||||
// 1.0858 and 1.0859); the units of appendix A give slightly different prices (EURUSD 1,000 / 921 = 1.08578, which gives
|
||||
// 2,714 pips at leverage 2, not 2,715). What the test checks is the formula 0.5 / leverage × price / pip on every cell.
|
||||
private static readonly (string Pair, decimal Price, int?[] Pips)[] Table65 =
|
||||
[
|
||||
("EURUSD", 1.0859m, [181, 271, 543, 1086, 2715]),
|
||||
|
||||
Reference in new issue
Block a user