Add C# (.NET) binding over the C ABI hub (#226)
The first language stecker on the C ABI hub: a .NET binding exposing all 514 indicators as idiomatic `IDisposable` classes, generated from `wickra.h`. ## What's here - **`bindings/csharp/`** — the `Wickra` .NET 8 package. `[LibraryImport]` source-generated P/Invoke (`NativeMethods.g.cs`) plus idiomatic wrappers (`Indicators.g.cs`), both generated from the committed `bindings/c/include/wickra.h`. The binding owns no indicator maths — it only marshals types across the C ABI. - **Marshalling, verified end-to-end against the native library.** Opaque handles cross as `nint` kept alive per call via a `SafeHandle`; `bool` as `[MarshalAs(U1)]` (Rust `bool` is one byte); a self-correcting `DllImportResolver` validates the loaded library actually exports the Wickra ABI. Tests cover one representative per FFI archetype (scalar, candle, pairwise, multi-output, bars, profile, values-profile, order-book / array-input) plus exact Sma reference values. - **NuGet packaging** — `dotnet pack` produces `Wickra.<version>.nupkg`; the release pipeline stages prebuilt native libraries under `runtimes/<rid>/native/` for six target triples (win/linux/osx × x64/arm64). - **`examples/csharp/`** — nine examples mirroring `examples/c/`: streaming, backtest, multi_timeframe, parallel_assets, three strategies, and fetch_btcusdt + live_binance. - **CI** — a `csharp` job on the three OSes builds the C ABI, tests the binding, and runs the offline examples. **Release** — a gated `csharp-publish` job packs and pushes to NuGet (gated on `NUGET_API_KEY`, independent of the GitHub-release job so a C# hiccup never blocks the C/C++ asset release). - **Docs consistency wave** — README, CONTRIBUTING, CHANGELOG, examples/README, the issue / PR templates, `sync-about.yml`, and `.gitattributes`. The native Python / Node / WASM bindings and the C ABI are untouched; this is additive. Publishing to NuGet stays gated behind the release tag and the secret.
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
namespace Wickra.Examples;
|
||||
|
||||
/// <summary>Summary statistics for a long-only equity curve.</summary>
|
||||
public sealed record EquityResult(double TotalReturnPct, double Sharpe, double MaxDrawdownPct, int Trades, double FinalEquity);
|
||||
|
||||
/// <summary>
|
||||
/// Minimal long-only backtest helper: turn a stream of per-bar fractional
|
||||
/// returns into a PnL / Sharpe / max-drawdown summary. The strategy examples
|
||||
/// produce the returns; this aggregates them.
|
||||
/// </summary>
|
||||
public static class Backtest
|
||||
{
|
||||
/// <param name="periodReturns">Per-bar fractional returns (0.01 == +1%).</param>
|
||||
/// <param name="trades">Number of position entries.</param>
|
||||
/// <param name="periodsPerYear">Annualisation factor for the Sharpe ratio.</param>
|
||||
public static EquityResult Summarize(IReadOnlyList<double> periodReturns, int trades, double periodsPerYear = 252.0)
|
||||
{
|
||||
double equity = 1.0, peak = 1.0, maxDrawdown = 0.0;
|
||||
foreach (var r in periodReturns)
|
||||
{
|
||||
equity *= 1.0 + r;
|
||||
peak = Math.Max(peak, equity);
|
||||
if (peak > 0)
|
||||
{
|
||||
maxDrawdown = Math.Max(maxDrawdown, (peak - equity) / peak);
|
||||
}
|
||||
}
|
||||
|
||||
var mean = periodReturns.Count > 0 ? periodReturns.Average() : 0.0;
|
||||
var variance = periodReturns.Count > 1
|
||||
? periodReturns.Sum(x => (x - mean) * (x - mean)) / (periodReturns.Count - 1)
|
||||
: 0.0;
|
||||
var stdDev = Math.Sqrt(variance);
|
||||
var sharpe = stdDev > 1e-12 ? mean / stdDev * Math.Sqrt(periodsPerYear) : 0.0;
|
||||
|
||||
return new EquityResult((equity - 1.0) * 100.0, sharpe, maxDrawdown * 100.0, trades, equity);
|
||||
}
|
||||
|
||||
/// <summary>Prints a one-line summary.</summary>
|
||||
public static void Print(string name, EquityResult r)
|
||||
{
|
||||
Console.WriteLine(
|
||||
$"{name,-26} return={r.TotalReturnPct,8:F2}% sharpe={r.Sharpe,6:F2} maxDD={r.MaxDrawdownPct,6:F2}% trades={r.Trades}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
namespace Wickra.Examples;
|
||||
|
||||
/// <summary>One OHLCV bar with a millisecond timestamp.</summary>
|
||||
public readonly record struct Bar(double Open, double High, double Low, double Close, double Volume, long Timestamp);
|
||||
|
||||
/// <summary>
|
||||
/// Deterministic synthetic market data plus a small OHLCV CSV loader, shared by
|
||||
/// the offline examples so they run without network access.
|
||||
/// </summary>
|
||||
public static class MarketData
|
||||
{
|
||||
/// <summary>A reproducible price path (trend + two cycles), no randomness.</summary>
|
||||
public static double[] SyntheticPrices(int count, double start = 100.0)
|
||||
{
|
||||
var prices = new double[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
prices[i] = start + 12.0 * Math.Sin(i * 0.05) + 5.0 * Math.Sin(i * 0.013) + i * 0.01;
|
||||
}
|
||||
|
||||
return prices;
|
||||
}
|
||||
|
||||
/// <summary>A reproducible OHLCV series derived from <see cref="SyntheticPrices"/>.</summary>
|
||||
public static Bar[] SyntheticCandles(int count, long startTimestamp = 0, long stepMs = 3_600_000)
|
||||
{
|
||||
var prices = SyntheticPrices(count + 1);
|
||||
var bars = new Bar[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var open = prices[i];
|
||||
var close = prices[i + 1];
|
||||
var high = Math.Max(open, close) + 0.5 + Math.Abs(Math.Sin(i * 0.7));
|
||||
var low = Math.Min(open, close) - 0.5 - Math.Abs(Math.Cos(i * 0.7));
|
||||
var volume = 1_000.0 + 500.0 * (1.0 + Math.Sin(i * 0.1));
|
||||
bars[i] = new Bar(open, high, low, close, volume, startTimestamp + i * stepMs);
|
||||
}
|
||||
|
||||
return bars;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads an OHLCV CSV. Accepts rows of <c>timestamp,open,high,low,close,volume</c>
|
||||
/// or <c>open,high,low,close,volume</c>; a non-numeric first row is treated as a header.
|
||||
/// </summary>
|
||||
public static Bar[] LoadOhlcvCsv(string path)
|
||||
{
|
||||
var bars = new List<Bar>();
|
||||
foreach (var rawLine in File.ReadLines(path))
|
||||
{
|
||||
var line = rawLine.Trim();
|
||||
if (line.Length == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var cols = line.Split(',');
|
||||
if (!double.TryParse(cols[0], System.Globalization.CultureInfo.InvariantCulture, out _) &&
|
||||
!long.TryParse(cols[0], out _))
|
||||
{
|
||||
continue; // header row
|
||||
}
|
||||
|
||||
double F(int i) => double.Parse(cols[i], System.Globalization.CultureInfo.InvariantCulture);
|
||||
|
||||
if (cols.Length >= 6)
|
||||
{
|
||||
bars.Add(new Bar(F(1), F(2), F(3), F(4), F(5), long.Parse(cols[0])));
|
||||
}
|
||||
else
|
||||
{
|
||||
bars.Add(new Bar(F(0), F(1), F(2), F(3), F(4), bars.Count));
|
||||
}
|
||||
}
|
||||
|
||||
return bars.ToArray();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user