Files
StockSharp/Tests/IndicatorTests.Reference.cs
mika@stocksharp.com 2189594de5 Check that values do something, not merely that they travel
Five things in the core promised behaviour nothing held them to, and the suite
was green on all of them for one reason: it checked that a value is carried
correctly, never that it changes an outcome.

A percent activation price is a distance from the market, and the contract says
the server snapshots the price at registration. Nothing read the flag, so the
raw number became the trigger - a buy stop written as "five percent" fired on
the first print and a sell stop written the same way rested at 5 and never fired
at all. The only test naming the flag round-tripped it through serialization,
which passed precisely because the value is stored correctly. Its two sibling
flags each had a behavioural test; this one never got one. It is now snapshotted
against the last price the venue printed - the only stream a stop ever fires
against - with registration refused outright when there is nothing to snapshot.
Take profit turns out to have carried none of the three flags, so both halves of
the protective pair go through one path, and a structural test walks the
interface so a fourth flag cannot be added without being honoured.

The GPU comparison allowed 2.5% of the compared value, five orders of magnitude
above what float32 can lose. It is now formed from the epsilon, the window a
kernel accumulates over and the scale it works at - and five kernels turn out to
compute something else. Jurik seeded its cascades on the first bar where the CPU
seeds them for the whole formation window; Ichimoku trimmed its Senkou B store
to the Kijun length, returning the previous bar's value whenever the two were
equal; VWAP accumulated a whole series in float32; SuperTrend and
NickRypockTrailingReverse pick a branch by comparing a price to a level, which
float32 rounds more coarsely than the step between them.

A candle builder's Timeout was a public setting no code read, its mechanism
commented out - gone, with nothing in any repo setting it. The pair strategy
template declared two securities and traded one - it trades both now.

And Sharpe and Sortino scored five returns spread over a year exactly as they
scored the same five over five days. The class declared Period and derived the
annualisation from it, so it always promised equal spans, but counted every PnL
report as one period and ignored the time it carried. Returns now close on that
grid: an idle period is a return of zero, a period opened with no capital
records none, and the tail waits for its own boundary. Reading time at all
exposed two further things - a report stamped with the default date would have
opened the grid in year 0001 and buried a run under seven hundred thousand empty
periods, measured at 382 times too low on every optimiser iteration, and Period
could be changed while a grid was open. Figures from before are not comparable:
a strategy that reports rarely now scores lower, which is the point.

The suite itself was deciding results by how loaded the machine was. Eighteen
waits had no deadline and hung rather than failed, seventy-two more stood in for
a condition with a sleep, and twenty-two method timeouts were no longer than the
wait inside them. What remains is the kind that must stay: a window held open to
prove something does not happen, a delay that is itself under test, the pacing
of a feed. Eighteen files each declared the same empty TestReceiver and nine
their own CreateSecurityId - those had drifted, four returning a fresh id and
four a fixed one, so they were not merged blindly. StorageTests and
IndicatorTests, at about 3900 and 3600 lines, are split into partial classes by
theme with every fully qualified name kept.

Left as a finding: the ratio grid is fed from two clocks - a position's local
time on one path, the engine's market time on the other - which differ by hours
in a backtest. Putting both on the connector's clock changes which timestamps
MaxProfitDate and MaxDrawdownDate carry, and that is a contract decision.
2026-09-19 12:56:18 +03:00

263 lines
10 KiB
C#

namespace StockSharp.Tests;
using System.Collections.Concurrent;
using System.Text;
/// <summary>
/// Runs against the committed reference data under Resources/IndicatorsData.
/// </summary>
partial class IndicatorTests
{
[TestMethod]
public async Task Process()
{
var time = new DateTime(2000, 1, 1, 0, 0, 0).UtcKind();
var tf = TimeSpan.FromDays(1);
var secId = Helper.CreateSecurity().ToSecurityId();
var candles = await LoadCandles(secId, time, tf);
// Every indicator is an independent run over the same read-only candle array (Check() clones the
// candles it feeds), so the sweep is parallelised. Failures are collected rather than thrown so
// that one broken indicator does not hide the others, and each entry names its indicator - the
// asserts inside Check() carry no name of their own.
var invalid = new ConcurrentBag<(Type type, Exception error)>();
Parallel.ForEach(GetIndicatorTypes(), type =>
{
try
{
var indicator = type.CreateIndicator();
var inputType = type.InputValue;
if (inputType == typeof(DecimalIndicatorValue))
indicator.Check(candles, data => data.ClosePrice);
else if (inputType == typeof(CandleIndicatorValue))
indicator.Check(candles, data => data);
else
throw new InvalidOperationException(inputType.To<string>());
}
catch (Exception ex)
{
invalid.Add((type.Indicator, ex));
}
});
if (!invalid.IsEmpty)
{
var msg = invalid.OrderBy(x => x.type.Name).Select(x => $"{x.type.Name}: {x.error.Message}").JoinN();
Fail($"Indicators failed ({invalid.Count}):{Environment.NewLine}{msg}");
}
}
/// <summary>
/// Both readers of a whole series - <c>IndicatorDataRunner.Check</c> and <c>CompareValue</c> - compare
/// nothing at all on a bar the indicator reports itself unformed on, so a sweep proves only as much as
/// the indicator forms early. That bound is what <see cref="IIndicator.NumValuesToInitialize"/> promises
/// a user: feed it that many final values and it is ready, and everything after them is a real value
/// that a reference run actually answers for. An indicator that quietly needs more leaves the front of
/// the series unchecked, and one that never forms is swept through with nothing checked at all.
/// </summary>
[TestMethod]
public async Task EveryIndicatorFormsWithinNumValuesToInitialize()
{
var time = new DateTime(2000, 1, 1, 0, 0, 0).UtcKind();
var tf = TimeSpan.FromDays(1);
var secId = Helper.CreateSecurityId();
var candles = await LoadCandles(secId, time, tf);
// These two decide they are formed from the values they see rather than from how many - the same
// pair NumValuesToInitialize excludes. The count they publish cannot be held to, but they still owe
// the weaker half of the promise: they have to become formed on a real series.
var dataDependent = new HashSet<Type>
{
typeof(AdaptiveLaguerreFilter),
typeof(DemandIndex),
};
var errors = new List<string>();
foreach (var type in GetIndicatorTypes())
{
var indicator = type.CreateIndicator();
var declared = indicator.NumValuesToInitialize;
var inputType = type.InputValue;
var formedAt = 0;
for (var i = 0; i < candles.Length; i++)
{
var candle = candles[i];
IIndicatorValue input;
if (inputType == typeof(DecimalIndicatorValue))
input = new DecimalIndicatorValue(indicator, candle.ClosePrice, candle.OpenTime) { IsFinal = true };
else if (inputType == typeof(CandleIndicatorValue))
input = new CandleIndicatorValue(indicator, candle) { IsFinal = true };
else
throw new InvalidOperationException(inputType.To<string>());
indicator.Process(input);
if (indicator.IsFormed)
{
formedAt = i + 1;
break;
}
}
var name = type.Indicator.Name;
if (formedAt == 0)
errors.Add($"{name}: never formed over {candles.Length} candles, so no value of it was ever compared.");
else if (formedAt > declared && !dataDependent.Contains(type.Indicator))
errors.Add($"{name}: asks for {declared} value(s) but was formed only after {formedAt}, leaving {formedAt - declared} bar(s) beyond the declared warm-up unchecked.");
}
if (errors.Count > 0)
{
var report = errors
.OrderBy(error => error, StringComparer.Ordinal)
.JoinN();
Fail($"Indicators not formed within NumValuesToInitialize ({errors.Count}):{Environment.NewLine}{report}");
}
}
// ---------------------------------------------------------------------------------------------------------
// Reference-vector generator for Resources/IndicatorsData/<Indicator>.txt.
//
// Those files are the pinned expected output of Process(), and are otherwise only ever read. This is the
// single place that knows how to write them, and it shares Render() with Process()'s own Check(), so the
// written format cannot drift away from the parsed one.
//
// A file is produced with the same feed Process() uses - the one the indicator declares through
// [IndicatorIn]. Changing that declaration therefore changes the reference data, and the file has to be
// regenerated in the same commit as the change.
//
// It never runs by accident: it is opt-in through the SS_INDICATORS_REGEN environment variable, and with the
// variable unset it does nothing at all.
//
// SS_INDICATORS_REGEN=verify Re-render every indicator and report how a fresh run compares to the
// committed data. Writes nothing. ALWAYS run this first. It must report no
// VALIDATED difference at all: that is the proof that the generator produces
// the same numbers Process() pins today, so a later rewrite only changes what
// was meant to change. If it does report one, the generator is wrong - fix
// the generator, never the data.
// SS_INDICATORS_REGEN=A,B,C Rewrite the files of these indicators only (by class name).
// SS_INDICATORS_REGEN=* Rewrite every file.
//
// The report separates two kinds of difference:
//
// VALIDATED a value Process() actually asserts on has changed. Never acceptable without an intended
// change of behaviour, and the only thing that makes verify fail.
// cosmetic the bytes differ somewhere Check() never looks - a warm-up row before the indicator is
// formed, or a reference row that stops short of today's column count. The committed files
// carry a good deal of this: they are older than several engine changes (complex values now
// back-fill an empty entry for every inner, some warm-up formulas were rewritten), and Check()
// deliberately tolerates it. Regenerating a file also normalises its cosmetic drift, which is
// why files are regenerated one by one rather than wholesale.
//
// Line ending is a hard-coded CRLF and the encoding is UTF-8 without BOM, matching the committed files, so
// the output is identical on every platform.
//
// set SS_INDICATORS_REGEN=verify && dotnet test StockSharp_Tests.slnx --filter GenerateReferenceData
// ---------------------------------------------------------------------------------------------------------
[TestMethod]
public async Task GenerateReferenceData()
{
const string modeVar = "SS_INDICATORS_REGEN";
const string verifyMode = "verify";
const string allMode = "*";
var mode = Environment.GetEnvironmentVariable(modeVar);
// Verifying by default: left to itself this compares the committed reference data against
// what the indicators produce now and fails on a real difference. The rewrite modes have to
// be asked for, because they REWRITE committed data - set {modeVar} to a name, to a
// comma-separated list, or to * for every out-of-date file.
var verify = mode.IsEmpty() || mode.EqualsIgnoreCase(verifyMode);
var requested = verify || mode == allMode
? null
: mode.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToHashSet(StringComparer.InvariantCultureIgnoreCase);
var time = new DateTime(2000, 1, 1, 0, 0, 0).UtcKind();
var tf = TimeSpan.FromDays(1);
var secId = Helper.CreateSecurity().ToSecurityId();
var candles = await LoadCandles(secId, time, tf);
var encoding = new UTF8Encoding(false);
var identical = new List<string>();
var cosmetic = new List<string>();
var validated = new List<string>();
var written = new List<string>();
foreach (var type in GetIndicatorTypes())
{
var name = type.Indicator.Name;
if (requested?.Remove(name) == false)
continue;
var indicator = type.CreateIndicator();
var inputType = type.InputValue;
IndicatorDataRunner.RenderedSeries rendered;
if (inputType == typeof(DecimalIndicatorValue))
rendered = indicator.Render(candles, data => data.ClosePrice);
else if (inputType == typeof(CandleIndicatorValue))
rendered = indicator.Render(candles, data => data);
else
throw new InvalidOperationException(inputType.To<string>());
var path = Path.Combine(Helper.ResFolder, "IndicatorsData", $"{name}.txt");
var content = encoding.GetBytes(string.Concat(rendered.Rows.Select(r => r + "\r\n")));
var current = File.Exists(path) ? File.ReadAllBytes(path) : null;
if (current is not null && current.SequenceEqual(content))
{
identical.Add(name);
continue;
}
if (current is null)
{
validated.Add($"{name}: no reference file yet");
}
else
{
var diffs = rendered.ValidatedDiffs(Do.Invariant(() => File.ReadAllLines(path)));
if (diffs.Length == 0)
cosmetic.Add($"{name} (formed from line {rendered.FormedFrom + 1})");
else
validated.Add($"{name}: {diffs.Length} validated difference(s), first {diffs.First()}");
}
if (verify)
continue;
File.WriteAllBytes(path, content);
written.Add(name);
}
if (requested?.Count > 0)
Fail($"Unknown indicator name(s) in {modeVar}: {requested.JoinCommaSpace()}");
if (verify)
{
var report = $"byte-identical: {identical.Count}, cosmetic drift only: {cosmetic.Count}, VALIDATED differences: {validated.Count}" +
$"{Environment.NewLine}cosmetic: {cosmetic.JoinCommaSpace()}" +
$"{Environment.NewLine}{validated.JoinN()}";
if (validated.Count > 0)
Fail(report);
Console.WriteLine(report);
return;
}
written.Count.AssertGreater(0, $"{modeVar}={mode} matched no out-of-date reference file.");
}
}