// Copyright (c) 2026 fxtradingguide.com
// SPDX-License-Identifier: MIT
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
namespace FxTradingGuide.Studies;
///
/// Report and fill helpers shared by the studies. The report deliberately has no return.
///
public static class StudyReport
{
public const double SpreadFraction = 0.0001;
public const double NotionalFraction = 0.10;
public const double StartingCash = 100_000;
public const double Margin = 1.0;
public static void AssertCausal(int length, Func compute)
{
var full = compute(length);
if (full.Length != length)
{
throw new InvalidOperationException($"signal length {full.Length} != {length}");
}
var step = Math.Max(1, length / 20);
var indexes = new List();
for (var i = 0; i < length; i += step)
{
indexes.Add(i);
}
if (indexes.Count == 0 || indexes[^1] != length - 1)
{
indexes.Add(length - 1);
}
foreach (var end in indexes)
{
var prefix = compute(end + 1);
if (prefix.Length != end + 1 || prefix[^1] != full[end])
{
throw new InvalidOperationException(
$"look-ahead at index {end}: prefix ends {prefix[^1]}, full series has {full[end]}");
}
}
}
public static void Write(string study, IReadOnlyList observations, IReadOnlyList desired)
{
var (signals, filled) = CountChanges(desired);
if (ExerciseFills(observations, desired) != filled)
{
throw new InvalidOperationException("fill count did not match the cost-path count");
}
var first = observations[0];
var last = observations[^1];
Console.WriteLine($"study: {study}");
Console.WriteLine("language: csharp");
Console.WriteLine("data_source: ECB statistics");
Console.WriteLine($"series: {SampleSeries.SeriesKey}");
Console.WriteLine($"series_title: {SampleSeries.SeriesTitle}");
Console.WriteLine($"period: {first.Date} to {last.Date}");
Console.WriteLine($"observations: {observations.Count}");
Console.WriteLine("price: one daily reference rate, copied into Open, High, Low and Close");
Console.WriteLine(
"costs: spread fraction 0.0001 of the rate, applied once against the trader; commission 0; swap not modelled; slippage not modelled");
Console.WriteLine("fills: next observation after the signal");
Console.WriteLine(
$"position: one position; notional 10 percent of cash; starting cash {StartingCash.ToString("0", CultureInfo.InvariantCulture)}; margin {Margin.ToString("0", CultureInfo.InvariantCulture)}; no leverage in this study");
Console.WriteLine("past_performance: Past performance does not predict future results");
Console.WriteLine("return_reported: no");
Console.WriteLine($"signals: {signals}");
Console.WriteLine($"filled_orders: {filled}");
Console.WriteLine("library_trades: n/a");
Console.WriteLine($"signal_digest: {Digest(desired)}");
Console.WriteLine("status: ok");
}
public static string Digest(IReadOnlyList desired)
{
var parts = new string[desired.Count];
for (var i = 0; i < desired.Count; i++)
{
parts[i] = desired[i] switch
{
null => ".",
-1 or 0 or 1 => desired[i]!.Value.ToString(CultureInfo.InvariantCulture),
_ => throw new InvalidOperationException($"signal out of range: {desired[i]}"),
};
}
var payload = Encoding.ASCII.GetBytes(string.Join(',', parts));
return Convert.ToHexString(SHA256.HashData(payload)).ToLowerInvariant();
}
public static double FillPrice(double rate, int side, double spread = SpreadFraction)
{
if (side is not (1 or -1))
{
throw new ArgumentOutOfRangeException(nameof(side), "fill side must be +1 or -1");
}
if (rate <= 0 || spread < 0)
{
throw new ArgumentOutOfRangeException(nameof(rate), "rate and spread must be positive");
}
return rate * (1.0 + (side * spread));
}
private static (int Signals, int Filled) CountChanges(IReadOnlyList desired)
{
var previous = 0;
var signals = 0;
var filled = 0;
for (var index = 0; index < desired.Count; index++)
{
if (desired[index] is not int value || value == previous)
{
continue;
}
signals++;
if (index + 1 < desired.Count)
{
filled++;
}
previous = value;
}
return (signals, filled);
}
private static int ExerciseFills(IReadOnlyList observations, IReadOnlyList desired)
{
if (observations.Count != desired.Count)
{
throw new ArgumentException("Signal length must match the series.");
}
var previous = 0;
var filled = 0;
for (var index = 0; index < desired.Count; index++)
{
if (desired[index] is not int value || value == previous)
{
continue;
}
if (index + 1 < desired.Count)
{
var side = value == 0 ? -previous : value;
_ = FillPrice(observations[index + 1].Rate, side);
filled++;
}
previous = value;
}
return filled;
}
}