Every intent of a strategy now crosses a risk engine that only refuses or shrinks: loss limits per world with the 24-hour block, the weekly halving, the halving and the switch on the fall from the high, the size limits on invested capital, single position, crypto share and trade risk, the technical checks, no short sales and no leverage, the day-trade guard (off by default). The switch, "Ferma tutto", "Ferma e chiudi", the STOP file and the orders-per-minute anomaly stop the bot until the user confirms a restart, and a restart after a trip measures the high from then on. The correctives of SPEC 8.5 (crypto regime, economic calendar) and the risk rules also run inside the backtests of the base strategies, so the reports show what would happen live. Each stage of a decision is written to a new decisions table with reason codes. The stage book is the only way to real money: an order on a real account needs the startup consent, every requirement of SPEC 12.3 met, the typed phrase and a fresh password and second factor. Order managers on real accounts fail closed and ask again before each order leaves. A demoted or revoked strategy keeps its real positions in exit only, with stops, until they are at zero. The simulated twin stays out of totals and of the reference equity. Tests cover each rule of 9.1 and 9.2, with property tests for "never larger than asked" and "never larger after a loss", and both proofs on a fake real account: nothing reaches it without the procedure, and a demoted strategy manages exits and stops down to zero. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2409e74b26
commit
8def84e122
25 files changed
+3737
-11
No files matched your search
@@ -52,7 +52,7 @@ public sealed class LaboratoryScreenTests
|
||||
"Esito del protocollo", "Risultato netto con costi doppi", "Deflated Sharpe Ratio", "Probabilità di sovra-adattamento (PBO)",
|
||||
"Risultato della variante scelta", "Comprare e tenere", "Risultato per anno", "Sensibilità ai costi", "Finestre che avanzano",
|
||||
"K-fold purgato combinatorio", "Nessuno sguardo in avanti", "nessuna è cambiata", "Tutte le varianti", "Cosa questo test non considera",
|
||||
"Fase 5", "Impronta dei dati", "Vedi i numeri in una tabella",
|
||||
"esempio: correttivi e limiti di rischio non si applicano", "Impronta dei dati", "Vedi i numeri in una tabella",
|
||||
})
|
||||
{
|
||||
StringAssert.Contains(report, part, $"Missing \"{part}\" in the report.");
|
||||
|
||||
@@ -68,7 +68,7 @@ public sealed class LaboratoryTests
|
||||
Assert.IsNotNull(report.Combinatorial);
|
||||
Assert.IsNotNull(report.Overfitting);
|
||||
Assert.IsTrue(report.Curve.Count is > 100 and <= TrialRunner.MaxCurvePoints + 1);
|
||||
Assert.IsTrue(report.Limitations.Any(l => l.Contains("Fase 5", StringComparison.Ordinal)));
|
||||
Assert.IsTrue(report.Limitations.Any(l => l.Contains("Strategia d'esempio", StringComparison.Ordinal)));
|
||||
|
||||
// A second trial of the same strategy deflates for the variants of both.
|
||||
var second = await lab.PlanAsync(Request() with { Grid = new Dictionary<string, IReadOnlyList<decimal>> { ["fast"] = [10m], ["slow"] = [30m] } },
|
||||
|
||||
@@ -0,0 +1,556 @@
|
||||
using Anubis.Core;
|
||||
using Anubis.Data;
|
||||
using Anubis.Db;
|
||||
using Anubis.Platform;
|
||||
using Anubis.Risk;
|
||||
using Anubis.Trading;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The risk engine at work on the database (issues #42, #43; SPEC 9, 12.3, 12.4): the gate of every order, the switch
|
||||
/// of each world, the STOP file, the orders per minute, the day-trade guard, and the only way to real money, tested
|
||||
/// against a fake real account (a simulator that says "live").
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class RiskEngineTests
|
||||
{
|
||||
private static readonly CancellationToken _none = CancellationToken.None;
|
||||
private static readonly TimeSpan _minute = TimeSpan.FromSeconds(60);
|
||||
private const string Password = "password-giusta";
|
||||
|
||||
private sealed class Setup : IAsyncDisposable
|
||||
{
|
||||
public required TradingRig Rig { get; init; }
|
||||
|
||||
public required SettingsStore Settings { get; init; }
|
||||
|
||||
public required StageBook Stages { get; init; }
|
||||
|
||||
public required RiskEngine Risk { get; init; }
|
||||
|
||||
public required AccountContext Account { get; init; }
|
||||
|
||||
public required Instrument Btc { get; init; }
|
||||
|
||||
public List<IDisposable> Owned { get; } = [];
|
||||
|
||||
public string? Folder { get; init; }
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
foreach (var owned in Owned)
|
||||
{
|
||||
owned.Dispose();
|
||||
}
|
||||
|
||||
if (Folder is not null)
|
||||
{
|
||||
TempFolder.Delete(Folder);
|
||||
}
|
||||
|
||||
await Rig.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A real-money consent as the startup configuration would give it: only for the fake real account of these tests.</summary>
|
||||
private static TradingConsent Consent() => TradingConsent.From(DockerPlatform.Load(new Dictionary<string, string?>
|
||||
{
|
||||
["ANUBIS_DB_ENGINE"] = "sqlite",
|
||||
["ANUBIS_SECRET_KEY"] = new string('k', 40),
|
||||
["ANUBIS_ADMIN_PASSWORD"] = "initial-pass-1",
|
||||
["ANUBIS_ALLOW_LIVE"] = "1",
|
||||
}));
|
||||
|
||||
/// <summary>crypto_trend in simulation on the OKX simulator with 10 000 €, BTC at 60 000.</summary>
|
||||
private static async Task<Setup> CreateAsync(TradingConsent? consent = null, bool stopFile = false)
|
||||
{
|
||||
var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||
var settings = new SettingsStore(rig.Db, rig.Clock, new EventBus());
|
||||
var stages = new StageBook(rig.Db, rig.Clock, consent ?? TradingConsent.None, (password, _, _) => Task.FromResult(password == Password));
|
||||
var folder = stopFile ? TempFolder.Create("stop") : null;
|
||||
var risk = new RiskEngine(rig.Db, rig.Clock, rig.Ledger, stages, settings, new FxStore(rig.Db, rig.Clock), rig.FindAsync, rig.QuoteAsync)
|
||||
{
|
||||
StopFile = folder is null ? null : Path.Combine(folder, "STOP"),
|
||||
};
|
||||
var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false);
|
||||
var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false);
|
||||
rig.Quote(btc.Symbol, 60_000m, 60_010m);
|
||||
await rig.Ledger.RecordCapitalAsync(account.AccountId, StrategyNames.CryptoTrend, 10_000m, "EUR", "test", _none).ConfigureAwait(false);
|
||||
await StageRowAsync(rig, StrategyNames.CryptoTrend, account.AccountId, StrategyStages.Simulation, rig.Clock.UtcNow).ConfigureAwait(false);
|
||||
return new Setup { Rig = rig, Settings = settings, Stages = stages, Risk = risk, Account = account, Btc = btc, Folder = folder };
|
||||
}
|
||||
|
||||
private static Task<int> StageRowAsync(TradingRig rig, string strategy, Guid account, string stage, DateTimeOffset since) =>
|
||||
rig.Db.WriteAsync(s => s.ExecuteAsync(
|
||||
"INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share, stage_since) VALUES (@id, @s, @a, @st, 0, @j, @t, @t, 1, @since)",
|
||||
_none, ("id", Ids.NewId(rig.Clock)), ("s", strategy), ("a", account), ("st", stage), ("j", new DbJson("{}")), ("t", rig.Clock.UtcNow), ("since", since)), _none);
|
||||
|
||||
private static TradeIntent Buy(Setup s, decimal quantity, string strategy = StrategyNames.CryptoTrend, Instrument? instrument = null) =>
|
||||
new((instrument ?? s.Btc).Id, strategy, OrderSide.Buy, quantity, OrderPurpose.Entry, Ids.NewId(s.Rig.Clock)) { StopLevel = 57_000m };
|
||||
|
||||
private static TradeIntent Sell(Setup s, decimal quantity, string strategy = StrategyNames.CryptoTrend, OrderPurpose purpose = OrderPurpose.Exit, Instrument? instrument = null) =>
|
||||
new((instrument ?? s.Btc).Id, strategy, OrderSide.Sell, quantity, purpose, Ids.NewId(s.Rig.Clock));
|
||||
|
||||
private static Task<FillOutcome> HoldAsync(Setup s, AccountContext account, decimal quantity, string strategy = StrategyNames.CryptoTrend, Instrument? instrument = null) =>
|
||||
s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(account, instrument ?? s.Btc, strategy, OrderSide.Buy, quantity, 60_000m), _none);
|
||||
|
||||
private static Task<int> SnapshotAsync(TradingRig rig, string world, DateTimeOffset at, decimal index) =>
|
||||
rig.Db.WriteAsync(s => s.ExecuteAsync(
|
||||
"INSERT INTO equity_snapshots (id, taken_at, scope, account_id, strategy, equity, cash, invested, drawdown_pct, created_at, world, currency, flows, twr_index, peak_index) " +
|
||||
"VALUES (@id, @t, 'total', NULL, NULL, @e, @e, 0, 0, @t, @w, 'EUR', 10000, @x, @x)", _none,
|
||||
("id", Ids.NewId(rig.Clock)), ("t", at), ("e", 10_000m * index), ("w", world), ("x", index)), _none);
|
||||
|
||||
private static Task<IReadOnlyList<string>> EventsAsync(TradingRig rig, string kind) =>
|
||||
rig.QueryAsync("SELECT severity FROM risk_events WHERE kind = @k", r => r.Text("severity"), ("k", kind));
|
||||
|
||||
// ---- The gate: stop, pause, ownership, sizes ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task PauseStopsEntriesAndStopStopsEverythingButProtection()
|
||||
{
|
||||
await using var s = await CreateAsync();
|
||||
await HoldAsync(s, s.Account, 0.01m);
|
||||
Assert.AreEqual(0.01m, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Quantity);
|
||||
|
||||
await s.Settings.SetAsync(SettingsStore.BotState.Key, "paused", "test");
|
||||
Assert.AreEqual(RiskReasons.BotPaused, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal);
|
||||
Assert.IsNull((await s.Risk.GateAsync(Sell(s, 0.01m), s.Account, _none)).Refusal, "exits go on in pause");
|
||||
|
||||
await s.Settings.SetAsync(SettingsStore.BotState.Key, "stopped", "test");
|
||||
Assert.AreEqual(RiskReasons.BotStopped, (await s.Risk.GateAsync(Sell(s, 0.01m), s.Account, _none)).Refusal, "no sales on the strategy's initiative");
|
||||
Assert.IsNull((await s.Risk.GateAsync(Sell(s, 0.01m, purpose: OrderPurpose.Protective), s.Account, _none)).Refusal, "protection always passes");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task NoShortSalesAndNothingThatTheStrategyDidNotBuy()
|
||||
{
|
||||
await using var s = await CreateAsync();
|
||||
Assert.AreEqual(RiskReasons.NotOwned, (await s.Risk.GateAsync(Sell(s, 0.01m), s.Account, _none)).Refusal, "a position the bot did not open is never touched");
|
||||
|
||||
await HoldAsync(s, s.Account, 0.01m);
|
||||
Assert.AreEqual(RiskReasons.OwnedByOther, (await s.Risk.GateAsync(Sell(s, 0.01m, StrategyNames.EquityMomentum), s.Account, _none)).Refusal);
|
||||
var more = await s.Risk.GateAsync(Sell(s, 0.05m), s.Account, _none);
|
||||
Assert.AreEqual(0.01m, more.Quantity);
|
||||
CollectionAssert.Contains(more.Reasons.ToList(), RiskReasons.NoShortSelling);
|
||||
Assert.AreEqual(RiskReasons.NoShortSelling, (await s.Risk.GateAsync(Buy(s, 0.01m) with { Purpose = OrderPurpose.Exit }, s.Account, _none)).Refusal);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task APurchaseIsShrunkAndTheDecisionRecordsWhy()
|
||||
{
|
||||
await using var s = await CreateAsync();
|
||||
var intent = Buy(s, 0.5m);
|
||||
var result = await s.Risk.GateAsync(intent, s.Account, _none);
|
||||
|
||||
// 0.5 BTC is three times the equity; 20% of it at 60 010 is 0.0333 BTC; the risk to the stop, 1% of 10 000 over 3 010, a little less.
|
||||
Assert.IsNull(result.Refusal);
|
||||
Assert.AreEqual(Math.Round(100m / 3_010m, 8), Math.Round(result.Quantity, 8));
|
||||
CollectionAssert.AreEqual(new[] { RiskReasons.InvestedLimit, RiskReasons.PositionLimit, RiskReasons.TradeRiskLimit }, result.Reasons.ToList(), string.Join(",", result.Reasons));
|
||||
var row = (await new DecisionLog(s.Rig.Db, s.Rig.Clock).OfAsync(intent.DecisionId, _none)).Single();
|
||||
Assert.AreEqual(DecisionStages.Risk, row.Stage);
|
||||
Assert.AreEqual(DecisionOutcomes.Reduced, row.Outcome);
|
||||
CollectionAssert.Contains(row.Reasons.ToList(), RiskReasons.TradeRiskLimit);
|
||||
Assert.IsTrue(row.Data!.ContainsKey("reference"));
|
||||
|
||||
// No leverage: with the rest of the bot ten times larger the limits allow more, the strategy's own cash does not.
|
||||
await s.Rig.Ledger.RecordCapitalAsync(s.Account.AccountId, "sma_cross", 90_000m, "EUR", "test", _none);
|
||||
var poor = await s.Risk.GateAsync(Buy(s, 0.5m), s.Account, _none);
|
||||
Assert.AreEqual(Math.Round(10_000m / 60_010m, 8), Math.Round(poor.Quantity, 8));
|
||||
Assert.AreEqual(RiskReasons.NoLeverage, poor.Reasons[^1]);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task OldPricesStopEntriesButNotExits()
|
||||
{
|
||||
await using var s = await CreateAsync();
|
||||
await HoldAsync(s, s.Account, 0.01m);
|
||||
s.Rig.Clock.Advance(TimeSpan.FromSeconds(61));
|
||||
Assert.AreEqual(RiskReasons.StalePrice, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal);
|
||||
Assert.IsNull((await s.Risk.GateAsync(Sell(s, 0.01m), s.Account, _none)).Refusal);
|
||||
|
||||
s.Rig.Refresh();
|
||||
var skewed = new RiskEngine(s.Rig.Db, s.Rig.Clock, s.Rig.Ledger, s.Stages, s.Settings, new FxStore(s.Rig.Db, s.Rig.Clock), s.Rig.FindAsync, s.Rig.QuoteAsync)
|
||||
{
|
||||
ClockSkew = _ => TimeSpan.FromSeconds(3),
|
||||
};
|
||||
Assert.AreEqual(RiskReasons.ClockSkew, (await skewed.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task AStrategyInObservationNeverBuys()
|
||||
{
|
||||
await using var s = await CreateAsync();
|
||||
await s.Rig.Db.WriteAsync(x => x.ExecuteAsync("UPDATE strategy_state SET stage = 'observation'", _none), _none);
|
||||
Assert.AreEqual(RiskReasons.Observation, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal);
|
||||
}
|
||||
|
||||
// ---- 9.2: the limits of each world ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task ADayOfLossesBlocksEntriesOfThatWorldOnly()
|
||||
{
|
||||
await using var s = await CreateAsync();
|
||||
var now = s.Rig.Clock.UtcNow;
|
||||
await SnapshotAsync(s.Rig, Worlds.Simulated, now - TimeSpan.FromHours(10), 1.00m);
|
||||
await SnapshotAsync(s.Rig, Worlds.Simulated, now, 0.975m);
|
||||
await SnapshotAsync(s.Rig, Worlds.Real, now - TimeSpan.FromHours(10), 1.00m);
|
||||
await SnapshotAsync(s.Rig, Worlds.Real, now, 1.01m);
|
||||
|
||||
var alerts = await s.Risk.CheckAsync([], _none);
|
||||
Assert.IsTrue(alerts.Any(a => a.Kind == RiskAlertKinds.DailyLoss));
|
||||
Assert.AreEqual(RiskSeverities.High, (await EventsAsync(s.Rig, RiskAlertKinds.DailyLoss)).Single());
|
||||
Assert.AreEqual(RiskReasons.DailyLossBlock, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal);
|
||||
Assert.IsFalse((await s.Risk.WorldAsync(Worlds.Real, _none)).EntriesBlocked, "the real world goes on");
|
||||
Assert.IsNotEmpty(await s.Rig.QueryAsync("SELECT code FROM journal WHERE code = @c", r => r.Text("code"), ("c", RiskAlertKinds.DailyLoss)), "the diary says it");
|
||||
|
||||
// A second check does not repeat the alert; after 24 hours entries are back.
|
||||
await s.Risk.CheckAsync([], _none);
|
||||
Assert.HasCount(1, await EventsAsync(s.Rig, RiskAlertKinds.DailyLoss));
|
||||
s.Rig.Clock.Advance(TimeSpan.FromHours(24) + _minute);
|
||||
s.Rig.Refresh();
|
||||
Assert.IsNull((await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheSwitchTripsAtFifteenPercentAndOnlyTheUserRestartsIt()
|
||||
{
|
||||
await using var s = await CreateAsync();
|
||||
await HoldAsync(s, s.Account, 0.01m);
|
||||
await SnapshotAsync(s.Rig, Worlds.Simulated, s.Rig.Clock.UtcNow, 1.00m);
|
||||
await s.Risk.CheckAsync([], _none);
|
||||
s.Rig.Clock.Advance(TimeSpan.FromDays(5));
|
||||
await SnapshotAsync(s.Rig, Worlds.Simulated, s.Rig.Clock.UtcNow, 1.20m);
|
||||
await s.Risk.CheckAsync([], _none);
|
||||
|
||||
// The high of ten days ago is outside the series read now, but remembered.
|
||||
s.Rig.Clock.Advance(TimeSpan.FromDays(10));
|
||||
s.Rig.Refresh();
|
||||
await SnapshotAsync(s.Rig, Worlds.Simulated, s.Rig.Clock.UtcNow, 1.00m);
|
||||
await s.Risk.CheckAsync([], _none);
|
||||
var world = await s.Risk.WorldAsync(Worlds.Simulated, _none);
|
||||
Assert.IsTrue(world.State.Tripped);
|
||||
Assert.AreEqual(RiskSeverities.Critical, (await EventsAsync(s.Rig, RiskAlertKinds.DrawdownStop)).Single());
|
||||
Assert.AreEqual(RiskReasons.SwitchTripped, (await s.Risk.GateAsync(Sell(s, 0.01m), s.Account, _none)).Refusal);
|
||||
Assert.IsFalse((await s.Risk.WorldAsync(Worlds.Real, _none)).State.Tripped);
|
||||
|
||||
// Days pass: nothing rearms by itself.
|
||||
s.Rig.Clock.Advance(TimeSpan.FromDays(3));
|
||||
await s.Risk.CheckAsync([], _none);
|
||||
Assert.IsTrue((await s.Risk.WorldAsync(Worlds.Simulated, _none)).State.Tripped);
|
||||
|
||||
await s.Risk.RestartAsync("utente", _none);
|
||||
world = await s.Risk.WorldAsync(Worlds.Simulated, _none);
|
||||
Assert.IsFalse(world.State.Tripped);
|
||||
Assert.AreEqual(0m, world.Measures.Drawdown, "the high starts again from now");
|
||||
Assert.AreEqual("active", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
|
||||
Assert.IsNotEmpty(await s.Rig.QueryAsync("SELECT key FROM config_history WHERE key = @k AND changed_by = 'utente'", r => r.Text("key"), ("k", SettingsStore.BotState.Key)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TenOrdersInAMinuteStopTheBot()
|
||||
{
|
||||
await using var s = await CreateAsync();
|
||||
async Task OrdersAsync(int count, string purpose)
|
||||
{
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
await s.Rig.Db.WriteAsync(x => x.ExecuteAsync(
|
||||
"INSERT INTO orders (id, account_id, instrument_id, strategy, client_order_id, side, order_type, quantity, status, created_at, updated_at, purpose, submitted_at) " +
|
||||
"VALUES (@id, @a, @i, 'crypto_trend', @c, 'buy', 'limit', 1, 'submitted', @t, @t, @p, @t)", _none,
|
||||
("id", Ids.NewId(s.Rig.Clock)), ("a", s.Account.AccountId), ("i", s.Btc.Id), ("c", "T" + Ids.NewId(s.Rig.Clock).ToString("N")), ("t", s.Rig.Clock.UtcNow), ("p", purpose)), _none);
|
||||
}
|
||||
}
|
||||
|
||||
await OrdersAsync(9, "entry");
|
||||
await OrdersAsync(5, "stop");
|
||||
await s.Risk.CheckAsync([], _none);
|
||||
Assert.AreEqual("active", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value, "stops do not count");
|
||||
|
||||
await OrdersAsync(1, "exit");
|
||||
await s.Risk.CheckAsync([], _none);
|
||||
Assert.AreEqual("stopped", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
|
||||
Assert.AreEqual(RiskSeverities.Critical, (await EventsAsync(s.Rig, RiskReasons.OrdersPerMinute)).Single());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheStopFileStopsEverythingAndBlocksTheRestart()
|
||||
{
|
||||
await using var s = await CreateAsync(stopFile: true);
|
||||
await File.WriteAllTextAsync(s.Risk.StopFile!, "");
|
||||
Assert.AreEqual(RiskReasons.BotStopped, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal, "at once, before the check");
|
||||
await s.Risk.CheckAsync([], _none);
|
||||
Assert.AreEqual("stopped", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
|
||||
await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => s.Risk.RestartAsync("utente", _none));
|
||||
|
||||
File.Delete(s.Risk.StopFile!);
|
||||
Assert.AreEqual(RiskReasons.BotStopped, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal, "removing the file does not restart");
|
||||
await s.Risk.RestartAsync("utente", _none);
|
||||
Assert.IsNull((await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task StopEverythingCancelsWorkOrdersButKeepsTheStops()
|
||||
{
|
||||
await using var s = await CreateAsync();
|
||||
var paper = s.Rig.Paper(PaperOptions.Okx(), s.Account.AccountId);
|
||||
await paper.DepositAsync(100_000m, "EUR", _none);
|
||||
var manager = s.Rig.Manager(paper, s.Account);
|
||||
await manager.SubmitAsync(Buy(s, 0.01m) with { StartAggressive = true }, _none);
|
||||
await s.Rig.TurnsAsync(manager, 2, _minute);
|
||||
var stops = await paper.GetOpenOrdersAsync(_none);
|
||||
Assert.HasCount(1, stops, "the stop of the position");
|
||||
|
||||
// A sale far from the price stays working; "Ferma tutto" cancels it and puts the stop back.
|
||||
s.Rig.Quote(s.Btc.Symbol, 60_000m, 60_010m);
|
||||
var held = (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Btc.Id, StrategyNames.CryptoTrend, _none))!.Quantity;
|
||||
await manager.SubmitAsync(Sell(s, held), _none);
|
||||
await s.Risk.StopAllAsync([manager], "utente", "stop_all", "Fermo tutto.", _none);
|
||||
await s.Rig.TurnsAsync(manager, 1, _minute);
|
||||
Assert.AreEqual("stopped", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
|
||||
Assert.AreEqual(held, (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Btc.Id, StrategyNames.CryptoTrend, _none))?.Quantity, "the position stays");
|
||||
var open = await paper.GetOpenOrdersAsync(_none);
|
||||
Assert.IsTrue(open.Any(o => o.Kind == OrderKind.Stop || o.StopPrice is not null), "the stop is there");
|
||||
Assert.IsEmpty(await s.Rig.QueryAsync("SELECT id FROM executions WHERE status = 'working'", r => r.Id("id")));
|
||||
}
|
||||
|
||||
// ---- 9.2: the day-trade guard ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheDayTradeGuardKeepsMeanReversionInAndCountsTheDay()
|
||||
{
|
||||
await using var s = await CreateAsync();
|
||||
var alpaca = await s.Rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Simulation);
|
||||
var stocks = new List<Instrument>();
|
||||
foreach (var symbol in new[] { "AAA", "BBB", "CCC", "DDD" })
|
||||
{
|
||||
var stock = await s.Rig.InstrumentAsync(TradingRig.Stock(symbol));
|
||||
s.Rig.Quote(symbol, 99.99m, 100m);
|
||||
stocks.Add(stock);
|
||||
}
|
||||
|
||||
await new FxStore(s.Rig.Db, s.Rig.Clock).UpsertAsync([new FxRate("EUR", "USD", DateOnly.FromDateTime(s.Rig.Clock.UtcNow.UtcDateTime), 1.10m, "test")], _none);
|
||||
await s.Rig.Ledger.RecordCapitalAsync(alpaca.AccountId, StrategyNames.EquityMeanrev, 5_000m, "USD", "test", _none);
|
||||
await s.Rig.Ledger.RecordCapitalAsync(alpaca.AccountId, StrategyNames.EquityMomentum, 5_000m, "USD", "test", _none);
|
||||
await s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(alpaca, stocks[0], StrategyNames.EquityMeanrev, OrderSide.Buy, 1m, 100m), _none);
|
||||
await s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(alpaca, stocks[1], StrategyNames.EquityMomentum, OrderSide.Buy, 1m, 100m), _none);
|
||||
|
||||
// Off by default: mean reversion may leave on the day it entered.
|
||||
Assert.IsNull((await s.Risk.GateAsync(Sell(s, 1m, StrategyNames.EquityMeanrev, instrument: stocks[0]), alpaca, _none)).Refusal);
|
||||
|
||||
await s.Settings.SetAsync(RiskSettings.PdtGuard.Key, "on", "test");
|
||||
Assert.AreEqual(RiskEngine.PdtReason, (await s.Risk.GateAsync(Sell(s, 1m, StrategyNames.EquityMeanrev, instrument: stocks[0]), alpaca, _none)).Refusal);
|
||||
Assert.IsNull((await s.Risk.GateAsync(Sell(s, 1m, StrategyNames.EquityMomentum, instrument: stocks[1]), alpaca, _none)).Refusal);
|
||||
|
||||
// Two positions opened today: one more allowed, then none.
|
||||
Assert.AreEqual(1, await s.Risk.PdtRoomAsync(alpaca.AccountId, _none));
|
||||
Assert.IsNull((await s.Risk.GateAsync(Buy(s, 1m, StrategyNames.EquityMomentum, stocks[2]) with { StopLevel = 99m }, alpaca, _none)).Refusal);
|
||||
await s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(alpaca, stocks[2], StrategyNames.EquityMomentum, OrderSide.Buy, 1m, 100m), _none);
|
||||
Assert.AreEqual(RiskEngine.PdtReason, (await s.Risk.GateAsync(Buy(s, 1m, StrategyNames.EquityMomentum, stocks[3]) with { StopLevel = 99m }, alpaca, _none)).Refusal);
|
||||
|
||||
// Crypto is not touched by it.
|
||||
Assert.IsNull((await s.Risk.GateAsync(Buy(s, 0.001m), s.Account, _none)).Refusal);
|
||||
}
|
||||
|
||||
// ---- 12.4: real money only with the procedure ----
|
||||
|
||||
private sealed record Live(FaultyBroker Broker, PaperBroker Paper, AccountContext Account, OrderManager Manager);
|
||||
|
||||
/// <summary>A fake real account: the simulator behind a broker that says "live", and its order manager wired as in the service.</summary>
|
||||
private static async Task<Live> FakeRealAccountAsync(Setup s, bool permit = true)
|
||||
{
|
||||
var account = await s.Rig.AccountAsync(Venues.Okx, TradingEnvironments.Live, "OKX reale (finto)");
|
||||
var paper = s.Rig.Paper(PaperOptions.Okx(), account.AccountId);
|
||||
await paper.DepositAsync(100_000m, "EUR", _none);
|
||||
var broker = new FaultyBroker(paper, TradingEnvironments.Live);
|
||||
var manager = new OrderManager(s.Rig.Db, s.Rig.Clock, s.Rig.Ledger, broker, account, TradingRig.Installation, s.Rig.FindAsync, s.Rig.QuoteAsync)
|
||||
{
|
||||
ConfirmPrice = s.Rig.QuoteAsync,
|
||||
MarketOpen = (_, _) => Task.FromResult(true),
|
||||
Gate = s.Risk.GateAsync,
|
||||
LivePermit = permit ? s.Stages.LiveRefusalAsync : null,
|
||||
};
|
||||
s.Owned.Add(manager);
|
||||
return new Live(broker, paper, account, manager);
|
||||
}
|
||||
|
||||
/// <summary>Everything SPEC 12.3 asks before reduced real: 60 days, 8 closed trades, the one-step comparison, the backtest passed.</summary>
|
||||
private static async Task RequirementsMetAsync(Setup s)
|
||||
{
|
||||
var since = s.Rig.Clock.UtcNow - TimeSpan.FromDays(61);
|
||||
await s.Rig.Db.WriteAsync(x => x.ExecuteAsync("UPDATE strategy_state SET stage_since = @t", _none, ("t", since)), _none);
|
||||
await s.Stages.ApplyQualificationAsync(StrategyNames.CryptoTrend, new Qualification
|
||||
{
|
||||
Passed = true,
|
||||
Verdict = "superato",
|
||||
Report = "docs/backtests/crypto_trend.md",
|
||||
MaxDrawdown = 0.20m,
|
||||
ExpectedSlippageBp = 5m,
|
||||
RoundTripCost = 0.004m,
|
||||
}, _none);
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
var closed = since + TimeSpan.FromDays(5 + (i * 6));
|
||||
await s.Rig.Db.WriteAsync(x => x.ExecuteAsync(
|
||||
"INSERT INTO trades (id, account_id, instrument_id, strategy, status, opened_at, closed_at, bought_quantity, bought_value, sold_quantity, sold_value, fees, realized, created_at, updated_at) " +
|
||||
"VALUES (@id, @a, @i, 'crypto_trend', 'closed', @o, @c, 0.01, 600, 0.01, 620, 1, 19, @c, @c)", _none,
|
||||
("id", Ids.NewId(s.Rig.Clock)), ("a", s.Account.AccountId), ("i", s.Btc.Id), ("o", closed - TimeSpan.FromDays(3)), ("c", closed)), _none);
|
||||
await new DecisionLog(s.Rig.Db, s.Rig.Clock).WriteAsync(new DecisionRow(Ids.NewId(s.Rig.Clock), StrategyNames.CryptoTrend, s.Account.AccountId, null, DecisionStages.OneStep,
|
||||
DecisionOutcomes.Same, [], null, closed), _none);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task NoOrderReachesARealAccountWithoutTheProcedure()
|
||||
{
|
||||
// Without the startup consent: nothing, however the strategy stands.
|
||||
await using (var s = await CreateAsync())
|
||||
{
|
||||
var live = await FakeRealAccountAsync(s);
|
||||
var (id, refusal) = await live.Manager.SubmitAsync(Buy(s, 0.001m), _none);
|
||||
Assert.IsNull(id);
|
||||
Assert.AreEqual(RiskReasons.NoConsent, refusal);
|
||||
await RequirementsMetAsync(s);
|
||||
var refused = await Assert.ThrowsExactlyAsync<LiveConfirmationException>(() => s.Stages.ConfirmLiveAsync(
|
||||
new LiveConfirmation(StrategyNames.CryptoTrend, live.Account.AccountId, StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Reduced), Password, null, "utente"), _none));
|
||||
Assert.AreEqual(RiskReasons.NoConsent, refused.Code);
|
||||
await s.Rig.TurnsAsync(live.Manager, 3, _minute);
|
||||
Assert.IsEmpty(live.Broker.Sent);
|
||||
}
|
||||
|
||||
// An order manager without the permission check sends nothing on a real account: it fails closed.
|
||||
await using (var s = await CreateAsync(Consent()))
|
||||
{
|
||||
var bare = await FakeRealAccountAsync(s, permit: false);
|
||||
Assert.AreEqual(RiskReasons.LiveNotConfirmed, (await bare.Manager.SubmitAsync(Buy(s, 0.001m), _none)).Refusal);
|
||||
Assert.IsEmpty(bare.Broker.Sent);
|
||||
}
|
||||
|
||||
// With the consent, step by step: every part of the procedure is needed.
|
||||
await using (var s = await CreateAsync(Consent()))
|
||||
{
|
||||
var live = await FakeRealAccountAsync(s);
|
||||
await s.Rig.Ledger.RecordCapitalAsync(live.Account.AccountId, StrategyNames.CryptoTrend, 2_500m, "EUR", "test", _none);
|
||||
Assert.AreEqual(RiskReasons.LiveNotConfirmed, (await live.Manager.SubmitAsync(Buy(s, 0.001m), _none)).Refusal, "simulation is not real money");
|
||||
await Assert.ThrowsExactlyAsync<LiveConfirmationException>(() => s.Stages.MoveAsync(StrategyNames.CryptoTrend, StrategyStages.Reduced, "test", "utente", _none),
|
||||
"no shortcut to real money");
|
||||
|
||||
var phrase = StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Reduced);
|
||||
LiveConfirmation Ask(string text, string password) => new(StrategyNames.CryptoTrend, live.Account.AccountId, text, password, null, "utente");
|
||||
Assert.AreEqual("requirements", (await Assert.ThrowsExactlyAsync<LiveConfirmationException>(() => s.Stages.ConfirmLiveAsync(Ask(phrase, Password), _none))).Code);
|
||||
|
||||
await RequirementsMetAsync(s);
|
||||
Assert.IsTrue((await s.Stages.RequirementsAsync(StrategyNames.CryptoTrend, _none)).All(r => r.Met));
|
||||
Assert.AreEqual("phrase", (await Assert.ThrowsExactlyAsync<LiveConfirmationException>(() => s.Stages.ConfirmLiveAsync(Ask("confermo", Password), _none))).Code);
|
||||
Assert.AreEqual("password", (await Assert.ThrowsExactlyAsync<LiveConfirmationException>(() => s.Stages.ConfirmLiveAsync(Ask(phrase, "sbagliata"), _none))).Code);
|
||||
await s.Rig.TurnsAsync(live.Manager, 2, _minute);
|
||||
Assert.IsEmpty(live.Broker.Sent, "nothing reached the real account before the confirmation");
|
||||
|
||||
s.Rig.Refresh();
|
||||
await s.Stages.ConfirmLiveAsync(Ask(phrase, Password), _none);
|
||||
var stage = (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!;
|
||||
Assert.AreEqual(StrategyStages.Reduced, stage.Stage);
|
||||
Assert.AreEqual(live.Account.AccountId, stage.LiveAccountId);
|
||||
Assert.IsNotNull(stage.LiveConfirmedAt);
|
||||
Assert.IsNotEmpty(await s.Rig.QueryAsync("SELECT key FROM config_history WHERE key = @k", r => r.Text("key"), ("k", "strategy.crypto_trend.stage")));
|
||||
Assert.IsNotEmpty(await s.Rig.QueryAsync("SELECT to_stage FROM strategy_stage_history WHERE to_stage = 'reduced'", r => r.Text("to_stage")));
|
||||
|
||||
var (id, refusal) = await live.Manager.SubmitAsync(Buy(s, 0.001m) with { StartAggressive = true }, _none);
|
||||
Assert.IsNull(refusal);
|
||||
Assert.IsNotNull(id);
|
||||
await s.Rig.TurnsAsync(live.Manager, 2, _minute);
|
||||
Assert.IsNotEmpty(live.Broker.Sent, "after the procedure the order reaches the account");
|
||||
|
||||
// Another strategy on the same account is still refused: the confirmation is for one strategy and one account.
|
||||
Assert.AreEqual(RiskReasons.LiveNotConfirmed, (await live.Manager.SubmitAsync(Buy(s, 0.001m, StrategyNames.EquityMomentum), _none)).Refusal);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Simulation)]
|
||||
public async Task ADemotedStrategyKeepsManagingItsRealPositionsDownToZero()
|
||||
{
|
||||
await using var s = await CreateAsync(Consent());
|
||||
var live = await FakeRealAccountAsync(s);
|
||||
await s.Rig.Ledger.RecordCapitalAsync(live.Account.AccountId, StrategyNames.CryptoTrend, 2_500m, "EUR", "test", _none);
|
||||
await RequirementsMetAsync(s);
|
||||
await s.Stages.ConfirmLiveAsync(new LiveConfirmation(StrategyNames.CryptoTrend, live.Account.AccountId,
|
||||
StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Reduced), Password, null, "utente"), _none);
|
||||
s.Rig.Refresh();
|
||||
await live.Manager.SubmitAsync(Buy(s, 0.002m) with { StartAggressive = true }, _none);
|
||||
await s.Rig.TurnsAsync(live.Manager, 3, _minute);
|
||||
var held = (await s.Rig.Ledger.PositionAsync(live.Account.AccountId, s.Btc.Id, StrategyNames.CryptoTrend, _none))!.Quantity;
|
||||
Assert.IsTrue(held is > 0.0019m and <= 0.002m, "bought, less the fee in bitcoin");
|
||||
Assert.HasCount(1, await live.Paper.GetOpenOrdersAsync(_none), "the stop on the real account");
|
||||
|
||||
await s.Stages.DemoteAsync(StrategyNames.CryptoTrend, "drawdown", _none);
|
||||
var stage = (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!;
|
||||
Assert.AreEqual(StrategyStages.Simulation, stage.Stage);
|
||||
Assert.IsTrue(stage.ExitOnly);
|
||||
Assert.IsNull(stage.LiveConfirmedAt);
|
||||
Assert.AreEqual(RiskSeverities.High, (await EventsAsync(s.Rig, "demotion")).Single());
|
||||
|
||||
// Nothing new, nothing bigger.
|
||||
var sent = live.Broker.Sent.Count;
|
||||
Assert.AreEqual(RiskReasons.ExitOnly, (await live.Manager.SubmitAsync(Buy(s, 0.001m), _none)).Refusal);
|
||||
|
||||
// The stops are kept and put back every day: one moved by hand comes back.
|
||||
foreach (var order in await live.Paper.GetOpenOrdersAsync(_none))
|
||||
{
|
||||
await live.Paper.CancelOrderAsync(order.ClientOrderId, order.Symbol, _none);
|
||||
}
|
||||
|
||||
await s.Rig.TurnsAsync(live.Manager, 2, _minute);
|
||||
Assert.HasCount(1, await live.Paper.GetOpenOrdersAsync(_none), "the stop is put back on the real account");
|
||||
|
||||
// The exit goes: half, then the rest.
|
||||
Assert.IsNull((await live.Manager.SubmitAsync(Sell(s, 0.001m) with { StartAggressive = true }, _none)).Refusal);
|
||||
await s.Rig.TurnsAsync(live.Manager, 3, _minute);
|
||||
var rest = (await s.Rig.Ledger.PositionAsync(live.Account.AccountId, s.Btc.Id, StrategyNames.CryptoTrend, _none))!.Quantity;
|
||||
Assert.AreEqual(held - 0.001m, rest);
|
||||
Assert.AreEqual(0, await s.Stages.ReleaseExitOnlyAsync(s.Rig.Ledger, _none), "a real position is still open");
|
||||
Assert.IsNull((await live.Manager.SubmitAsync(Sell(s, rest) with { StartAggressive = true }, _none)).Refusal);
|
||||
await s.Rig.TurnsAsync(live.Manager, 3, _minute);
|
||||
Assert.IsNull(await s.Rig.Ledger.PositionAsync(live.Account.AccountId, s.Btc.Id, StrategyNames.CryptoTrend, _none) is { Quantity: > 0m } p ? p : null);
|
||||
Assert.IsTrue(live.Broker.Sent.Count > sent);
|
||||
|
||||
// At zero the exit only ends, and the real account is closed to it again.
|
||||
Assert.AreEqual(1, await s.Stages.ReleaseExitOnlyAsync(s.Rig.Ledger, _none));
|
||||
Assert.IsFalse((await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!.ExitOnly);
|
||||
Assert.AreEqual(RiskReasons.LiveNotConfirmed, (await live.Manager.SubmitAsync(Buy(s, 0.001m), _none)).Refusal);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheTwinIsPhotographedButLeftOutOfTheTotals()
|
||||
{
|
||||
await using var s = await CreateAsync(Consent());
|
||||
var live = await s.Rig.AccountAsync(Venues.Okx, TradingEnvironments.Live, "OKX reale (finto)");
|
||||
await s.Rig.Ledger.RecordCapitalAsync(live.AccountId, StrategyNames.CryptoTrend, 2_500m, "EUR", "test", _none);
|
||||
await s.Rig.Db.WriteAsync(x => x.ExecuteAsync("UPDATE strategy_state SET stage = 'reduced', live_account_id = @a, live_confirmed_at = @t", _none,
|
||||
("a", live.AccountId), ("t", s.Rig.Clock.UtcNow)), _none);
|
||||
await new EquityBook(s.Rig.Db, s.Rig.Clock, s.Rig.Ledger, new FxStore(s.Rig.Db, s.Rig.Clock)).TakeAsync(_none);
|
||||
var totals = await s.Rig.QueryAsync("SELECT world, equity FROM equity_snapshots WHERE scope = 'total'", r => (World: r.Text("world"), Equity: r.Money("equity")));
|
||||
Assert.AreEqual(2_500m, totals.Single(t => t.World == Worlds.Real).Equity);
|
||||
Assert.IsFalse(totals.Any(t => t.World == Worlds.Simulated), "the twin is the only simulated ledger");
|
||||
Assert.HasCount(2, await s.Rig.QueryAsync("SELECT id FROM equity_snapshots WHERE scope = 'strategy'", r => r.Id("id")));
|
||||
|
||||
// In the risk engine too: the twin's ten thousand are not exposure, and the reference counts the quarter four times.
|
||||
var exposure = await s.Risk.ExposureAsync(_none);
|
||||
Assert.AreEqual(0m, exposure.SimulatedEquity);
|
||||
Assert.AreEqual(2_500m, exposure.RealEquity);
|
||||
Assert.AreEqual(10_000m, await s.Risk.ReferenceAsync(_none));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
using Anubis.Backtest;
|
||||
using Anubis.Data;
|
||||
using Anubis.Risk;
|
||||
using Anubis.Strategies;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The rules of the risk engine without a database (issues #41, #42; SPEC 8.5, 9.1, 9.2, 9.5): every size rule, the
|
||||
/// monitor of losses with its blocks, warnings and switch, the scenarios, the correctives.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class RiskTests
|
||||
{
|
||||
private static readonly RiskLimits _limits = RiskLimits.Default;
|
||||
|
||||
// A Wednesday in November: 11:00 in Rome.
|
||||
private static readonly DateTimeOffset _now = new(2026, 11, 11, 10, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private static PurchaseRequest Request(decimal wanted, decimal price = 100m, decimal held = 0m, decimal? stop = 95m, decimal reference = 10_000m) => new()
|
||||
{
|
||||
Price = price,
|
||||
Held = held,
|
||||
Wanted = wanted,
|
||||
Stop = stop,
|
||||
WorldEquity = reference,
|
||||
WorldInvested = 0m,
|
||||
Reference = reference,
|
||||
};
|
||||
|
||||
// ---- 9.2: each limit on the size of a purchase ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheInvestedCapitalLimitStopsPurchasesAtTheEquity()
|
||||
{
|
||||
var size = RiskRules.SizePurchase(Request(10m) with { WorldInvested = 9_700m }, _limits);
|
||||
Assert.AreEqual(3m, size.Quantity);
|
||||
CollectionAssert.Contains(size.Reasons.ToList(), RiskReasons.InvestedLimit);
|
||||
Assert.AreEqual(0m, RiskRules.SizePurchase(Request(10m) with { WorldInvested = 10_000m }, _limits).Quantity);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void OnePositionNeverWeighsMoreThanTwentyPercentOfTheReference()
|
||||
{
|
||||
// 20% of 10 000 at 100 is 20 shares: 15 held, 5 more allowed.
|
||||
var size = RiskRules.SizePurchase(Request(10m, held: 15m, stop: 99.5m), _limits);
|
||||
Assert.AreEqual(5m, size.Quantity);
|
||||
CollectionAssert.Contains(size.Reasons.ToList(), RiskReasons.PositionLimit);
|
||||
|
||||
// Heavier than the threshold: the excess goes at the first chance.
|
||||
Assert.AreEqual(10m, RiskRules.Excess(30m, 100m, 10_000m, _limits));
|
||||
Assert.AreEqual(0m, RiskRules.Excess(20m, 100m, 10_000m, _limits));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void CryptoNeverGoesBeyondFortyPercentOfTheReference()
|
||||
{
|
||||
var size = RiskRules.SizePurchase(Request(10m, stop: 99.5m) with { IsCrypto = true, CryptoValue = 3_900m }, _limits);
|
||||
Assert.AreEqual(1m, size.Quantity);
|
||||
CollectionAssert.Contains(size.Reasons.ToList(), RiskReasons.CryptoLimit);
|
||||
|
||||
// The same purchase of a stock is not touched by the crypto share.
|
||||
Assert.AreEqual(10m, RiskRules.SizePurchase(Request(10m, stop: 99.5m) with { CryptoValue = 3_900m }, _limits).Quantity);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheRiskOfOneTradeIsAtMostOnePercentOnTheWholePosition()
|
||||
{
|
||||
// 1% of 10 000 is 100; with the stop 10 below the price that is 10 shares for the whole position.
|
||||
var size = RiskRules.SizePurchase(Request(15m, stop: 90m), _limits);
|
||||
Assert.AreEqual(10m, size.Quantity);
|
||||
CollectionAssert.Contains(size.Reasons.ToList(), RiskReasons.TradeRiskLimit);
|
||||
Assert.AreEqual(6m, RiskRules.SizePurchase(Request(15m, held: 4m, stop: 90m), _limits).Quantity);
|
||||
|
||||
// Without a stop the whole value is at risk; a stop at or above the price buys nothing.
|
||||
Assert.AreEqual(1m, RiskRules.SizePurchase(Request(15m, stop: null), _limits).Quantity);
|
||||
var above = RiskRules.SizePurchase(Request(15m, stop: 100m), _limits);
|
||||
Assert.AreEqual(0m, above.Quantity);
|
||||
CollectionAssert.Contains(above.Reasons.ToList(), RiskReasons.StopAbovePrice);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void AReductionMultipliesTheTargetAndNeverSellsWhatIsHeld()
|
||||
{
|
||||
var halved = RiskRules.SizePurchase(Request(10m, stop: 99.5m) with { Multiplier = 0.5m }, _limits);
|
||||
Assert.AreEqual(5m, halved.Quantity);
|
||||
CollectionAssert.Contains(halved.Reasons.ToList(), RiskReasons.Reduction);
|
||||
|
||||
// 6 held towards a target of 10, halved to 5: nothing more is bought, nothing is sold.
|
||||
Assert.AreEqual(0m, RiskRules.SizePurchase(Request(4m, held: 6m, stop: 99.5m) with { Multiplier = 0.5m }, _limits).Quantity);
|
||||
}
|
||||
|
||||
// ---- 9.1 points 5 and 6, as properties ----
|
||||
|
||||
private sealed record Case(PurchaseRequest Request, decimal Loss, decimal Cut)
|
||||
{
|
||||
public override string ToString() => $"{Request} loss {Loss} cut {Cut}";
|
||||
}
|
||||
|
||||
private static Case Generate(Gen g)
|
||||
{
|
||||
var price = (decimal)Math.Round(1 + (g.Double() * 1000), 2);
|
||||
var reference = (decimal)Math.Round(1_000 + (g.Double() * 100_000), 2);
|
||||
var request = new PurchaseRequest
|
||||
{
|
||||
Price = price,
|
||||
Held = g.Bool() ? 0m : (decimal)Math.Round(g.Double() * 50, 4),
|
||||
Wanted = (decimal)Math.Round(g.Double() * 100, 4),
|
||||
Stop = g.Int(0, 4) switch
|
||||
{
|
||||
0 => null,
|
||||
1 => price * 1.01m,
|
||||
_ => Math.Round(price * (decimal)(0.5 + (g.Double() * 0.49)), 2),
|
||||
},
|
||||
Multiplier = g.Bool() ? 1m : (decimal)Math.Round(g.Double(), 2),
|
||||
WorldEquity = reference,
|
||||
WorldInvested = (decimal)Math.Round(g.Double() * (double)reference, 2),
|
||||
Reference = reference,
|
||||
IsCrypto = g.Bool(),
|
||||
CryptoValue = (decimal)Math.Round(g.Double() * 0.5 * (double)reference, 2),
|
||||
};
|
||||
return new Case(request, (decimal)Math.Round(g.Double() * 0.5, 4), (decimal)Math.Round(g.Double(), 4));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void NoRuleEverEnlargesWhatTheStrategyAsked() =>
|
||||
Property.ForAll(Generate, c =>
|
||||
{
|
||||
var size = RiskRules.SizePurchase(c.Request, _limits);
|
||||
Assert.IsTrue(size.Quantity >= 0m && size.Quantity <= c.Request.Wanted, $"{size.Quantity} for {c.Request.Wanted}");
|
||||
});
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void AfterALossNoPurchaseIsLarger() =>
|
||||
Property.ForAll(Generate, c =>
|
||||
{
|
||||
// The same purchase after a loss: less equity, a lower reference, a multiplier no higher. No doubling, no recovery.
|
||||
var before = RiskRules.SizePurchase(c.Request, _limits).Quantity;
|
||||
var factor = 1m - c.Loss;
|
||||
var after = RiskRules.SizePurchase(c.Request with
|
||||
{
|
||||
WorldEquity = c.Request.WorldEquity * factor,
|
||||
Reference = c.Request.Reference * factor,
|
||||
Multiplier = c.Request.Multiplier * (1m - (c.Cut / 2m)),
|
||||
}, _limits).Quantity;
|
||||
Assert.IsTrue(after <= before, $"{after} after the loss, {before} before");
|
||||
});
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void NoCorrectiveRaisesAWeight()
|
||||
{
|
||||
var holdings = new Dictionary<string, Holding> { ["AAA"] = new(10m, 100m, 90m, StrategyData.Start) };
|
||||
var bars = StrategyData.Series(StrategyData.FromCloses([100, 100, 100]));
|
||||
var context = new StrategyContext(StrategyData.Start.AddDays(2), default, ["AAA", "BBB"], new PortfolioView(9_000m, 10_000m, holdings), _ => bars, _ => null);
|
||||
Property.ForAll(g => (Symbol: g.Bool() ? "AAA" : "BBB", Target: (decimal)Math.Round(g.Double() * 0.5, 4), Multiplier: (decimal)Math.Round(g.Double() * 1.5, 4)), c =>
|
||||
{
|
||||
var intent = new Intent(c.Symbol, c.Target, "test") { Stop = 90m };
|
||||
var reduced = BookWeights.Reduce(context, intent, c.Multiplier, CorrectiveReasons.CalendarEvent);
|
||||
Assert.IsTrue(reduced.TargetWeight is null || reduced.TargetWeight <= c.Target, reduced.ToString());
|
||||
});
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheCodeCallsNoWithdrawalOrTransferEndpoint()
|
||||
{
|
||||
// SPEC 9.1 point 2: OKX withdrawals and transfers, Alpaca transfers and bank links, in any form.
|
||||
var endpoint = new System.Text.RegularExpressions.Regex(@"asset/withdrawal|asset/transfer|/transfers\b|ach_relationships|recipient_banks|/withdraw",
|
||||
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
var offenders = Repo.Files()
|
||||
.Where(f => f.Extension == ".cs" && Repo.Relative(f).StartsWith("src", StringComparison.Ordinal))
|
||||
.Where(f => endpoint.IsMatch(File.ReadAllText(f.FullName)))
|
||||
.Select(Repo.Relative)
|
||||
.ToList();
|
||||
Assert.IsEmpty(offenders, string.Join(", ", offenders));
|
||||
Assert.IsTrue(Repo.Files().Count(f => f.Extension == ".cs" && Repo.Relative(f).StartsWith("src", StringComparison.Ordinal)) > 50, "the scan sees the code");
|
||||
}
|
||||
|
||||
// ---- 9.2: the monitor of losses ----
|
||||
|
||||
private static List<IndexPoint> Points(params (double HoursAgo, decimal Index)[] points) =>
|
||||
[.. points.Select(p => new IndexPoint(_now - TimeSpan.FromHours(p.HoursAgo), p.Index)).OrderBy(p => p.At)];
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheDayStartsAtMidnightInItaly()
|
||||
{
|
||||
Assert.AreEqual(new DateTimeOffset(2026, 11, 10, 23, 0, 0, TimeSpan.Zero), RiskMonitor.ItalianMidnight(_now));
|
||||
Assert.AreEqual(new DateTimeOffset(2026, 7, 10, 22, 0, 0, TimeSpan.Zero), RiskMonitor.ItalianMidnight(new DateTimeOffset(2026, 7, 11, 8, 0, 0, TimeSpan.Zero)));
|
||||
|
||||
// A fall at 23:30 in Rome of the day before belongs to yesterday.
|
||||
var m = RiskMeasures.From(Points((24, 1.00m), (11.5, 0.97m), (0, 0.97m)), _now, null);
|
||||
Assert.AreEqual(0m, m.DayChange);
|
||||
Assert.AreEqual(-0.03m, m.Drawdown);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void ALossOfTwoPercentInADayBlocksEntriesForTwentyFourHours()
|
||||
{
|
||||
var m = RiskMeasures.From(Points((12, 1.00m), (0, 0.975m)), _now, null);
|
||||
var reading = RiskMonitor.Step(RiskMonitorState.Initial, m, _now, _limits);
|
||||
Assert.AreEqual(_now + TimeSpan.FromHours(24), reading.State.DailyBlockUntil);
|
||||
Assert.IsTrue(reading.Alerts.Any(a => a.Kind == RiskAlertKinds.DailyLoss));
|
||||
Assert.IsTrue(RiskMonitor.EntriesBlocked(reading.State, _now + TimeSpan.FromHours(23)), "24 hours, not until midnight");
|
||||
Assert.IsFalse(RiskMonitor.EntriesBlocked(reading.State, _now + TimeSpan.FromHours(25)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void ALossOfFivePercentInAWeekHalvesRiskForSevenDays()
|
||||
{
|
||||
var m = RiskMeasures.From(Points((24 * 7.5, 1.00m), (24 * 6, 0.96m), (12, 0.95m), (0, 0.948m)), _now, null);
|
||||
Assert.IsTrue(m.WeekChange <= -0.05m);
|
||||
var reading = RiskMonitor.Step(RiskMonitorState.Initial, m, _now, _limits);
|
||||
Assert.IsNull(reading.State.DailyBlockUntil);
|
||||
Assert.AreEqual(0.5m, RiskMonitor.Multiplier(reading.State, RiskMeasures.None, _now + TimeSpan.FromDays(6), _limits));
|
||||
Assert.AreEqual(1m, RiskMonitor.Multiplier(reading.State, RiskMeasures.None, _now + TimeSpan.FromDays(7.1), _limits));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheFallFromTheHighHalvesAtTenAndTripsTheSwitchAtFifteen()
|
||||
{
|
||||
var half = RiskMonitor.Step(RiskMonitorState.Initial, new RiskMeasures(0m, 0m, -0.11m), _now, _limits);
|
||||
Assert.AreEqual(0.5m, RiskMonitor.Multiplier(half.State, half.Measures, _now, _limits));
|
||||
Assert.IsFalse(half.State.Tripped);
|
||||
Assert.AreEqual(1, half.Alerts.Count(a => a.Kind == RiskAlertKinds.DrawdownHalf));
|
||||
Assert.AreEqual(0, RiskMonitor.Step(half.State, half.Measures, _now, _limits).Alerts.Count(a => a.Kind == RiskAlertKinds.DrawdownHalf), "said once");
|
||||
|
||||
var stop = RiskMonitor.Step(half.State, new RiskMeasures(0m, 0m, -0.16m), _now, _limits);
|
||||
Assert.IsTrue(stop.State.Tripped);
|
||||
Assert.IsTrue(RiskMonitor.EntriesBlocked(stop.State, _now + TimeSpan.FromDays(30)), "only the user restarts it");
|
||||
Assert.AreEqual(RiskSeverities.Critical, stop.Alerts.Single(a => a.Kind == RiskAlertKinds.DrawdownStop).Severity);
|
||||
|
||||
// With the week's halving too the purchases are a quarter.
|
||||
var both = half.State with { WeeklyHalvingUntil = _now + TimeSpan.FromDays(3) };
|
||||
Assert.AreEqual(0.25m, RiskMonitor.Multiplier(both, half.Measures, _now, _limits));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void AtEightyPercentOfAThresholdOneWarningAndNoBlock()
|
||||
{
|
||||
var near = new RiskMeasures(-0.017m, 0m, -0.017m);
|
||||
var first = RiskMonitor.Step(RiskMonitorState.Initial, near, _now, _limits);
|
||||
Assert.AreEqual(1, first.Alerts.Count(a => a.Kind == RiskAlertKinds.Warning), "the day's loss; the fall is far from 8%");
|
||||
Assert.IsFalse(RiskMonitor.EntriesBlocked(first.State, _now));
|
||||
Assert.AreEqual(1m, RiskMonitor.Multiplier(first.State, near, _now, _limits));
|
||||
Assert.AreEqual(0, RiskMonitor.Step(first.State, near, _now, _limits).Alerts.Count, "one for each crossing");
|
||||
|
||||
var back = RiskMonitor.Step(first.State, RiskMeasures.None, _now, _limits);
|
||||
Assert.AreEqual(1, RiskMonitor.Step(back.State, near, _now, _limits).Alerts.Count, "a new crossing warns again");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void ARestartAfterATripMeasuresTheHighFromNow()
|
||||
{
|
||||
var series = Points((48, 1.00m), (0, 0.84m));
|
||||
var tripped = RiskMonitor.Step(RiskMonitorState.Initial, RiskMeasures.From(series, _now, null), _now, _limits).State;
|
||||
Assert.IsTrue(tripped.Tripped);
|
||||
Assert.AreEqual(1.00m, tripped.Peak);
|
||||
|
||||
var restarted = RiskMonitor.Restart(tripped, _now);
|
||||
Assert.IsFalse(restarted.Tripped);
|
||||
Assert.IsNull(restarted.Peak);
|
||||
var later = _now + TimeSpan.FromHours(1);
|
||||
var after = RiskMeasures.From([.. series, new IndexPoint(later, 0.84m)], later, restarted.PeakFrom, restarted.Peak);
|
||||
Assert.AreEqual(0m, after.Drawdown, "otherwise the switch would trip again at once");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheHighIsRememberedBeyondTheSeriesRead() =>
|
||||
Assert.AreEqual(Math.Round((1.0m / 1.2m) - 1m, 6), Math.Round(RiskMeasures.From(Points((1, 1.0m), (0, 1.0m)), _now, null, knownPeak: 1.2m).Drawdown, 6));
|
||||
|
||||
// ---- 9.2: technical checks ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TechnicalChecksStopEntriesOnOldPricesFarLimitsAndAWrongClock()
|
||||
{
|
||||
Assert.IsNull(RiskRules.TechnicalRefusal(_now, _now - TimeSpan.FromSeconds(59), 100m, 100.9m, TimeSpan.FromSeconds(1), _limits));
|
||||
Assert.AreEqual(RiskReasons.StalePrice, RiskRules.TechnicalRefusal(_now, _now - TimeSpan.FromSeconds(61), 100m, null, null, _limits));
|
||||
Assert.AreEqual(RiskReasons.StalePrice, RiskRules.TechnicalRefusal(_now, null, null, null, null, _limits));
|
||||
Assert.AreEqual(RiskReasons.PriceGap, RiskRules.TechnicalRefusal(_now, _now, 100m, 101.5m, null, _limits));
|
||||
Assert.AreEqual(RiskReasons.ClockSkew, RiskRules.TechnicalRefusal(_now, _now, 100m, null, TimeSpan.FromSeconds(-3), _limits));
|
||||
}
|
||||
|
||||
// ---- Settings of the limits ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void LimitsComeFromSettingsAndRaisingOneIsRecognised()
|
||||
{
|
||||
var values = RiskSettings.Limits.ToDictionary(d => d.Key, d => d.Default);
|
||||
Assert.AreEqual(RiskLimits.Default, RiskSettings.From(k => values[k]));
|
||||
values[RiskSettings.DailyLoss.Key] = "3";
|
||||
var looser = RiskSettings.From(k => values[k]);
|
||||
Assert.AreEqual(0.03m, looser.DailyLoss);
|
||||
Assert.IsTrue(RiskLimits.Default.RaisedBy(looser));
|
||||
Assert.IsFalse(looser.RaisedBy(RiskLimits.Default), "lowering a limit needs no confirmation");
|
||||
Assert.IsNotNull(RiskSettings.DailyLoss.Check!("50"));
|
||||
Assert.AreEqual("off", RiskSettings.PdtGuard.Default, "the day-trade guard is off by default");
|
||||
}
|
||||
|
||||
// ---- 9.5: scenarios ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void ScenariosWithAndWithoutStops()
|
||||
{
|
||||
var positions = new[]
|
||||
{
|
||||
new ScenarioPosition(true, 2_000m, 1_800m),
|
||||
new ScenarioPosition(false, 3_000m, 2_700m),
|
||||
new ScenarioPosition(false, 1_000m, null),
|
||||
};
|
||||
var result = Scenarios.Compute(Scenarios.Default, positions, dollarAccountEur: 4_000m, equityEur: 10_000m);
|
||||
Assert.AreEqual(-400m, result[0].WithoutStops);
|
||||
Assert.AreEqual(-0.04m, result[0].WithoutStopsShare);
|
||||
Assert.AreEqual(-200m, result[0].WithStops, "the stop limits the loss");
|
||||
Assert.AreEqual(-280m, result[1].WithoutStops);
|
||||
Assert.AreEqual(-280m, result[1].WithStops, "a 7% fall stays above the stop; without a stop the whole loss");
|
||||
Assert.AreEqual(-680m, result[2].WithoutStops);
|
||||
Assert.AreEqual(-200m, result[3].WithoutStops);
|
||||
Assert.IsTrue(result[3].SameWithStops);
|
||||
Assert.IsNull(result[3].WithStops, "stops do not reduce the dollar");
|
||||
|
||||
// Rounded to 5 euro.
|
||||
Assert.AreEqual(-25m, Scenarios.Compute([new("x", -0.2m, 0m, 0m)], [new ScenarioPosition(true, 113m, null)], 0m, 1_000m)[0].WithStops);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void ScenariosAreASettingTheUserCanWrite()
|
||||
{
|
||||
CollectionAssert.AreEqual(Scenarios.Default.ToList(), Scenarios.Parse(Scenarios.Setting.Default).ToList(), "round trip");
|
||||
Assert.AreEqual(Scenarios.Default.Count, Scenarios.Parse(Scenarios.Setting.Default).Count);
|
||||
var custom = Scenarios.Parse("Crollo; −30; −10,5; 0");
|
||||
Assert.AreEqual(-0.105m, custom[0].Stocks);
|
||||
Assert.IsNotNull(Scenarios.Setting.Check!("solo testo"));
|
||||
Assert.IsNotNull(Scenarios.Setting.Check!("x; -200; 0; 0"));
|
||||
Assert.IsNull(Scenarios.Setting.Check!(Scenarios.Setting.Default));
|
||||
}
|
||||
|
||||
// ---- 8.5: correctives ----
|
||||
|
||||
private static CalendarEvent Event(string kind, DateTimeOffset at, string impact = "High", string currency = "USD") =>
|
||||
new(kind, "evento", at, true, "test", kind + at.ToString("O", System.Globalization.CultureInfo.InvariantCulture)) { Currency = currency, Impact = impact };
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheCalendarBlocksAroundImportantEvents()
|
||||
{
|
||||
var cpi = Event(CalendarEventKinds.Economic, _now);
|
||||
Assert.AreEqual((_now - TimeSpan.FromMinutes(30), _now + TimeSpan.FromMinutes(30)), CalendarBlocks.Window(cpi));
|
||||
Assert.IsNull(CalendarBlocks.Window(Event(CalendarEventKinds.Economic, _now, impact: "Medium")));
|
||||
Assert.IsNull(CalendarBlocks.Window(Event(CalendarEventKinds.Economic, _now, currency: "EUR")));
|
||||
Assert.AreEqual(_now + TimeSpan.FromMinutes(60), CalendarBlocks.Window(Event(CalendarEventKinds.CentralBank, _now, currency: "EUR"))!.Value.To);
|
||||
|
||||
// Two windows that overlap make one block; outside it the entry goes now.
|
||||
var fed = Event(CalendarEventKinds.CentralBank, _now + TimeSpan.FromMinutes(45));
|
||||
Assert.AreEqual(_now + TimeSpan.FromMinutes(105), CalendarBlocks.BlockedUntil(_now - TimeSpan.FromMinutes(10), [cpi, fed]));
|
||||
Assert.IsNull(CalendarBlocks.BlockedUntil(_now - TimeSpan.FromHours(2), [cpi, fed]));
|
||||
|
||||
// Tried again at the end of the window, or dropped when the deadline comes first.
|
||||
Assert.AreEqual(_now + TimeSpan.FromMinutes(30), CalendarBlocks.RetryAt(_now, [cpi], _now + TimeSpan.FromHours(1)));
|
||||
Assert.IsNull(CalendarBlocks.RetryAt(_now, [cpi], _now + TimeSpan.FromMinutes(10)));
|
||||
Assert.AreEqual(new DateTimeOffset(2026, 11, 11, 12, 0, 0, TimeSpan.Zero), CalendarBlocks.CryptoDeadline(_now));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheCalendarStageTurnsEntriesIntoNothingButKeepsStops()
|
||||
{
|
||||
var bars = StrategyData.Series(StrategyData.FromCloses([100, 100, 100]));
|
||||
var holdings = new Dictionary<string, Holding> { ["AAA"] = new(10m, 100m, 90m, StrategyData.Start) };
|
||||
var context = new StrategyContext(StrategyData.Start.AddDays(2), _now, ["AAA", "BBB"], new PortfolioView(9_000m, 10_000m, holdings), _ => bars, _ => null);
|
||||
var stage = new CalendarStage(_ => [Event(CalendarEventKinds.Economic, _now)]);
|
||||
var result = stage.Apply(context, [new Intent("AAA", 0.3m, "more") { Stop = 92m }, new Intent("BBB", 0.1m, "new") { Stop = 90m }, new Intent("CCC", 0m, "exit")]);
|
||||
Assert.IsNull(result[0].TargetWeight);
|
||||
Assert.AreEqual(92m, result[0].Stop, "the stop of a held position still follows the strategy");
|
||||
Assert.IsNull(result[1].TargetWeight);
|
||||
Assert.IsNull(result[1].Stop);
|
||||
CollectionAssert.Contains(result[1].Adjustments.ToList(), CorrectiveReasons.CalendarEvent);
|
||||
Assert.AreEqual(0m, result[2].TargetWeight, "exits pass");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void TheCryptoRegimeIsRiskyBelowTheAverageOrWithHighVolatility()
|
||||
{
|
||||
var settings = new CryptoRegimeSettings();
|
||||
Assert.IsNull(CryptoRegime.Risky(StrategyData.Series(StrategyData.SteadyRise(400)), settings));
|
||||
|
||||
var falling = StrategyData.FromCloses([.. Enumerable.Range(0, 260).Select(i => i < 230 ? 100.0 + i : 330.0 - (5 * (i - 229)))]);
|
||||
Assert.AreEqual(CorrectiveReasons.CryptoRegimeAverage, CryptoRegime.Risky(StrategyData.Series(falling), settings));
|
||||
|
||||
// Calm for two years, then a week of large swings while the price stays above its average.
|
||||
var closes = Enumerable.Range(0, 800).Select(i => 100.0 * Math.Pow(1.002, i) * (1 + (0.002 * (i % 2)))).ToList();
|
||||
for (var i = 790; i < 800; i++)
|
||||
{
|
||||
closes[i] = closes[789] * (i % 2 == 0 ? 1.08 : 1.0);
|
||||
}
|
||||
|
||||
Assert.AreEqual(CorrectiveReasons.CryptoRegimeVolatility, CryptoRegime.Risky(StrategyData.Series(StrategyData.FromCloses(closes)), settings));
|
||||
}
|
||||
|
||||
// ---- The risk engine inside the backtest ----
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void InTheBacktestAPositionTooHeavyComesBackToTheThreshold()
|
||||
{
|
||||
var bars = StrategyData.Series(StrategyData.FromCloses([100, 100, 100]));
|
||||
var holdings = new Dictionary<string, Holding> { ["AAA"] = new(30m, 100m, 90m, StrategyData.Start) };
|
||||
var day = StrategyData.Start.AddDays(2);
|
||||
var context = new StrategyContext(day, BacktestRisk.At(day), ["AAA"], new PortfolioView(7_000m, 10_000m, holdings), _ => bars, _ => StrategyData.Share("AAA"))
|
||||
{
|
||||
History = [new EquityMark(day, 10_000m, 3_000m)],
|
||||
};
|
||||
var result = new BacktestRisk().Apply(context, []);
|
||||
var cut = result.Single();
|
||||
Assert.AreEqual("AAA", cut.Symbol);
|
||||
Assert.AreEqual(0.2m, cut.TargetWeight);
|
||||
CollectionAssert.Contains(cut.Adjustments.ToList(), RiskReasons.PositionLimit);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
public void InTheBacktestNewEntriesStopAfterADayOfLosses()
|
||||
{
|
||||
var bars = StrategyData.Series(StrategyData.FromCloses([100, 100, 100]));
|
||||
var day = StrategyData.Start.AddDays(2);
|
||||
var context = new StrategyContext(day, BacktestRisk.At(day), ["AAA"], new PortfolioView(9_700m, 9_700m, new Dictionary<string, Holding>()), _ => bars,
|
||||
_ => StrategyData.Share("AAA"))
|
||||
{
|
||||
History = [new EquityMark(day.AddDays(-1), 10_000m, 0m), new EquityMark(day, 9_700m, 0m)],
|
||||
};
|
||||
var risk = new BacktestRisk();
|
||||
var result = risk.Apply(context, [new Intent("AAA", 0.1m, "entry") { Stop = 95m }]);
|
||||
Assert.IsNull(result[0].TargetWeight);
|
||||
CollectionAssert.Contains(result[0].Adjustments.ToList(), RiskReasons.DailyLossBlock);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user