Add the event-driven backtest engine and the strategy interface (refs #34)

The strategy contract of SPEC 5.3 (IStrategy, StrategyContext, Intent) is
shared by backtest and live: the context exposes bars only up to the
decision, adjusted and anchored to that day, and reading past it throws.
The engine runs each session as ordered events (corporate actions, open,
session, close), decides on the close and executes at the next open with
the simulator's price lists, slippage tiers, tick and lot rounding,
minimums and no leverage. Corrective and risk hooks are wired in and pass
everything through until Phase 5. One decision cycle can restart from a
recorded book (SPEC 12.3).

A scripted toy strategy reproduces a result computed by hand to the cent
on OKX and Alpaca costs. The Phase 3 class Trading.Strategies becomes
StrategyNames so the Anubis.Strategies namespace can exist.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 09:29:01 +01:00
1 parent 6d3ef8e7b5
commit d97304d7b9
19 files changed
+1592 -78

No files matched your search

+285
View File
@@ -0,0 +1,285 @@
using Anubis.Backtest;
using Anubis.Data;
using Anubis.Strategies;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>A strategy that says what it is told on given days: its result can be computed by hand.</summary>
internal sealed class ScriptedStrategy(IReadOnlyDictionary<DateOnly, IReadOnlyList<Intent>> script) : IStrategy
{
public string Id => "scripted";
public string Version => "1";
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
public IReadOnlyList<string> Universe(UniverseContext context) => context.Available;
public IReadOnlyList<Intent> Decide(StrategyContext context) => script.GetValueOrDefault(context.Day) ?? [];
}
internal static class BacktestData
{
public static readonly DateOnly D1 = new(2026, 1, 5);
public static InstrumentSpec Btc() => new(Venues.Okx, "BTC-EUR", "Bitcoin", AssetClasses.Crypto, "EUR")
{
BaseCurrency = "BTC",
TickSize = 0.1m,
LotSize = 0.00000001m,
MinSize = 0.00001m,
Status = "live",
};
public static InstrumentSpec Stock(string symbol = "AAPL") => new(Venues.Alpaca, symbol, symbol, AssetClasses.Equity, "USD")
{
Fractionable = true,
Status = "active",
Exchange = "NASDAQ",
};
/// <summary>Five sessions (open, high, low, close) on consecutive days from <see cref="D1"/>.</summary>
public static IReadOnlyList<DailyBar> FiveDays() =>
[
new(D1, 100, 101, 99, 100, 1000),
new(D1.AddDays(1), 100, 102, 99, 101, 1000),
new(D1.AddDays(2), 102, 104, 101, 103, 1000),
new(D1.AddDays(3), 103, 106, 102, 105, 1000),
new(D1.AddDays(4), 106, 107, 104, 106, 1000),
];
public static BacktestDataset One(InstrumentSpec spec, IReadOnlyList<DailyBar> bars, IReadOnlyList<CorporateAction>? actions = null) =>
new([new BacktestInstrument(spec, bars, actions)], spec.QuoteCurrency);
/// <summary>A random walk with a fixed seed: the same series at every run.</summary>
public static IReadOnlyList<DailyBar> Walk(int days, ulong seed, double start = 100, double drift = 0.0003, double volatility = 0.02, DateOnly? from = null)
{
var gen = new Gen((int)(seed % int.MaxValue));
var bars = new List<DailyBar>(days);
var close = start;
var day = from ?? new DateOnly(2018, 1, 1);
for (var i = 0; i < days; i++)
{
var open = close;
var change = drift + (volatility * gen.Normal());
close = Math.Round(open * Math.Exp(change), 2);
var high = Math.Round(Math.Max(open, close) * (1 + (0.005 * gen.Double())), 2);
var low = Math.Round(Math.Min(open, close) * (1 - (0.005 * gen.Double())), 2);
bars.Add(new DailyBar(day.AddDays(i), open, high, low, close, 1000));
}
return bars;
}
}
/// <summary>The event engine, its costs and its records (issue #34, SPEC 12.1).</summary>
[TestClass]
public sealed class BacktestTests
{
private static readonly DateOnly D1 = BacktestData.D1;
private static ScriptedStrategy Script(params (DateOnly Day, Intent[] Intents)[] steps) =>
new(steps.ToDictionary(s => s.Day, s => (IReadOnlyList<Intent>)s.Intents));
[TestMethod]
[TestCategory(Category.Unit)]
public void AToyStrategyGivesExactlyTheResultComputedByHand()
{
// Half the capital in bitcoin at the first close, everything out at the third. By hand, with OKX's
// price list (0,20% taker kept in the coin bought, 5 bp of slippage, 0,1 € tick):
// buy at the open of day 2: 100 × 1,0005 = 100,05 → tick up → 100,1; 50 BTC = 5.005,00 €; fee 0,1 BTC
// received 49,9 BTC; cash 10.000 − 5.005 = 4.995,00 €
// sell at the open of day 4: 103 × 0,9995 = 102,9485 → tick down → 102,9; 49,9 × 102,9 = 5.134,71 €;
// fee 0,2% = 10,26942 €; cash 4.995 + 5.124,44058 = 10.119,44058 €
var strategy = Script((D1, [new Intent("BTC-EUR", 0.5m, "enter")]), (D1.AddDays(2), [new Intent("BTC-EUR", 0m, "exit")]));
var run = BacktestEngine.Run(strategy, BacktestData.One(BacktestData.Btc(), BacktestData.FiveDays()), new BacktestOptions { InitialCapital = 10_000m });
Assert.AreEqual(10_119.44058m, run.FinalEquity);
Assert.AreEqual(119.44058m, run.NetResult);
Assert.HasCount(2, run.Fills);
Assert.AreEqual(new BacktestFill(D1.AddDays(1), "BTC-EUR", OrderSide.Buy, 50m, 100.1m, 5_005m, 10.01m, "enter"), run.Fills[0]);
Assert.AreEqual(new BacktestFill(D1.AddDays(3), "BTC-EUR", OrderSide.Sell, 49.9m, 102.9m, 5_134.71m, 10.26942m, "exit"), run.Fills[1]);
Assert.AreEqual(20.27942m, run.Fees);
var trade = run.Trades.Single();
Assert.AreEqual(new BacktestTrade("BTC-EUR", D1.AddDays(1), D1.AddDays(3), 5_005m, 119.44058m, 20.27942m), trade);
// Valued at every close: cash plus 49,9 BTC at 101 and 103 while held.
CollectionAssert.AreEqual(
new[] { 10_000m, 10_034.9m, 10_134.7m, 10_119.44058m, 10_119.44058m },
run.Equity.Select(e => e.Equity).ToArray());
Assert.IsEmpty(run.Notes);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheSameToyOnAStockPaysTheRegulatoryFeesRoundedUp()
{
// Alpaca: no commission, CAT 0,000003 $ a share on both sides and SEC 0,0000206 on sales, each rounded
// up to the cent; price step 0,01 $ above 1 $. By hand:
// buy 50 at 100 × 1,0005 = 100,05: 5.002,50 $ + CAT 0,01 → cash 4.997,49 $
// sell 50 at 103 × 0,9995 = 102,9485 → 102,94: 5.147,00 $ − SEC 0,11 − CAT 0,01 → cash 10.144,37 $
var strategy = Script((D1, [new Intent("AAPL", 0.5m, "enter")]), (D1.AddDays(2), [new Intent("AAPL", 0m, "exit")]));
var run = BacktestEngine.Run(strategy, BacktestData.One(BacktestData.Stock(), BacktestData.FiveDays()));
Assert.AreEqual(10_144.37m, run.FinalEquity);
Assert.AreEqual(0.13m, run.Fees);
Assert.AreEqual(new BacktestTrade("AAPL", D1.AddDays(1), D1.AddDays(3), 5_002.5m, 144.37m, 0.13m), run.Trades.Single());
}
[TestMethod]
[TestCategory(Category.Unit)]
public void StopsFillAtTheirLevelOrAtTheOpenWhenThePriceGapsBelow()
{
// Touched during the session: the low of day 2 (99) reaches the stop at 99,5, sold at 99,5 less slippage.
var touched = Script((D1, [new Intent("BTC-EUR", 0.5m, "enter") { Stop = 99.5m }]));
var run = BacktestEngine.Run(touched, BacktestData.One(BacktestData.Btc(), BacktestData.FiveDays()));
var sale = run.Fills.Single(f => f.Side == OrderSide.Sell);
Assert.AreEqual((D1.AddDays(1), 99.4m, BacktestReasons.Stop), (sale.Day, sale.Price, sale.Reason));
Assert.AreEqual(4_995m + 4_960.06m - 9.92012m, run.FinalEquity);
// Opened below: the stop raised to 102,5 at the close of day 2 meets an open of 102 and sells there (trap 24).
var gapped = Script((D1, [new Intent("BTC-EUR", 0.5m, "enter")]), (D1.AddDays(1), [new Intent("BTC-EUR", null, "raise_stop") { Stop = 102.5m }]));
run = BacktestEngine.Run(gapped, BacktestData.One(BacktestData.Btc(), BacktestData.FiveDays()));
sale = run.Fills.Single(f => f.Side == OrderSide.Sell);
Assert.AreEqual((D1.AddDays(2), 101.9m, BacktestReasons.StopGap), (sale.Day, sale.Price, sale.Reason));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ASplitChangesSharesAndStopsButNotTheValueAndSignalsSeeOneSeries()
{
// A 2-for-1 split with ex-date on day 4: real prices halve, the adjusted series does not jump.
var bars = BacktestData.FiveDays().Select((b, i) => i >= 3 ? b with { Open = b.Open / 2, High = b.High / 2, Low = b.Low / 2, Close = b.Close / 2 } : b).ToList();
var split = new CorporateAction("AAPL", CorporateActionKinds.Split, D1.AddDays(3), "test", "s1") { Ratio = 2m };
var seen = new List<double>();
var strategy = new Recording(seen, Script((D1, [new Intent("AAPL", 0.5m, "enter") { Stop = 90m }])));
var run = BacktestEngine.Run(strategy, BacktestData.One(BacktestData.Stock(), bars, [split]));
// 50 shares became 100, the stop 90 became 45: nothing was sold and the value went on with the price.
Assert.HasCount(1, run.Fills);
Assert.AreEqual(4_997.49m + (100m * 53m), run.FinalEquity);
// What the strategy saw on the last day: one continuous series in today's prices, no halving.
CollectionAssert.AreEqual(new[] { 50d, 50.5, 51.5, 52.5, 53 }, seen.ToArray());
}
[TestMethod]
[TestCategory(Category.Unit)]
public void PurchasesNeverBorrowAndOrdersBelowTheMinimumAreNotSent()
{
// Two instruments at weight 0,8 each: the second purchase is cut to the cash left, never past it.
var data = new BacktestDataset(
[new BacktestInstrument(BacktestData.Btc(), BacktestData.FiveDays()), new BacktestInstrument(BacktestData.Btc() with { Symbol = "ETH-EUR", BaseCurrency = "ETH" }, BacktestData.FiveDays())],
"EUR");
var run = BacktestEngine.Run(Script((D1, [new Intent("BTC-EUR", 0.8m, "a"), new Intent("ETH-EUR", 0.8m, "b")])), data);
Assert.IsTrue(run.Equity.All(e => e.Cash >= 0m), "Cash never goes below zero.");
Assert.IsTrue(run.Notes.Any(n => n.Symbol == "ETH-EUR" && n.Reason == BacktestReasons.NoCash));
// A purchase worth less than the minimum size is not sent and the note says why.
run = BacktestEngine.Run(Script((D1, [new Intent("BTC-EUR", 0.00000001m, "tiny")])), BacktestData.One(BacktestData.Btc(), BacktestData.FiveDays()));
Assert.IsEmpty(run.Fills);
Assert.AreEqual(OrderReasons.BelowMinimumSize, run.Notes.Single().Reason);
// Short selling is refused (SPEC 9.1).
run = BacktestEngine.Run(Script((D1, [new Intent("BTC-EUR", -0.5m, "short")])), BacktestData.One(BacktestData.Btc(), BacktestData.FiveDays()));
Assert.IsEmpty(run.Fills);
Assert.AreEqual(BacktestReasons.NoShortSelling, run.Notes.Single().Reason);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void DoubleCostsCostMoreAndTheSameInputsGiveTheSameRun()
{
var data = BacktestData.One(BacktestData.Btc(), BacktestData.Walk(400, 7));
var strategy = new MovingAverageCross(10, 40);
var once = BacktestEngine.Run(strategy, data);
var again = BacktestEngine.Run(new MovingAverageCross(10, 40), data);
CollectionAssert.AreEqual(once.Equity.ToArray(), again.Equity.ToArray());
CollectionAssert.AreEqual(once.Fills.ToArray(), again.Fills.ToArray());
Assert.IsGreaterThan(4, once.Trades.Count);
var doubled = BacktestEngine.Run(strategy, data, new BacktestOptions { Costs = new CostModel(2m) });
Assert.IsGreaterThan(once.Fees, doubled.Fees);
Assert.IsLessThan(once.FinalEquity, doubled.FinalEquity);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TheCorrectivesAndRiskHooksSeeEveryIntentAndCanChangeIt()
{
var seen = new List<string>();
var block = new Hook("risk", (ctx, intents) =>
{
seen.AddRange(intents.Select(i => i.Symbol));
return [];
});
var run = BacktestEngine.Run(Script((D1, [new Intent("BTC-EUR", 0.5m, "enter")])), BacktestData.One(BacktestData.Btc(), BacktestData.FiveDays()), new BacktestOptions { Risk = block });
CollectionAssert.AreEqual(new[] { "BTC-EUR" }, seen);
Assert.IsEmpty(run.Fills);
Assert.HasCount(1, run.Decisions[0].Proposed);
Assert.IsEmpty(run.Decisions[0].Final);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void OneCycleRestartsFromARecordedBook()
{
// The live book holds 49,9 BTC since day 2: the strategy decides on day 3 as if the backtest had run till then.
var book = new PortfolioState(4_995m, new Dictionary<string, Holding> { ["BTC-EUR"] = new(49.9m, 100.3m, null, D1.AddDays(1)) });
var exitWhenHeld = new ExitIfHeld();
var record = BacktestEngine.DecideOnce(exitWhenHeld, BacktestData.One(BacktestData.Btc(), BacktestData.FiveDays()), book, D1.AddDays(2));
Assert.AreEqual(D1.AddDays(2), record.Day);
Assert.AreEqual(new Intent("BTC-EUR", 0m, "held"), record.Proposed.Single());
Assert.AreEqual(4_995m + (49.9m * 103m), exitWhenHeld.Equity, "The book is valued at that day's close.");
}
private sealed class Recording(List<double> seen, IStrategy inner) : IStrategy
{
public string Id => inner.Id;
public string Version => inner.Version;
public IReadOnlyList<DecisionTime> Schedule() => inner.Schedule();
public IReadOnlyList<string> Universe(UniverseContext context) => inner.Universe(context);
public IReadOnlyList<Intent> Decide(StrategyContext context)
{
var bars = context.Bars("AAPL");
if (bars.Count == 5)
{
seen.AddRange(bars.Closes(5));
}
return inner.Decide(context);
}
}
private sealed class Hook(string name, Func<StrategyContext, IReadOnlyList<Intent>, IReadOnlyList<Intent>> apply) : IIntentStage
{
public string Name => name;
public IReadOnlyList<Intent> Apply(StrategyContext context, IReadOnlyList<Intent> intents) => apply(context, intents);
}
private sealed class ExitIfHeld : IStrategy
{
public decimal Equity { get; private set; }
public string Id => "exit_if_held";
public string Version => "1";
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
public IReadOnlyList<string> Universe(UniverseContext context) => context.Available;
public IReadOnlyList<Intent> Decide(StrategyContext context)
{
Equity = context.Portfolio.Equity;
return [.. context.Universe.Where(context.Portfolio.Holds).Select(s => new Intent(s, 0m, "held"))];
}
}
}
+1 -1
View File
@@ -29,7 +29,7 @@ public abstract class BrokerConformance
protected abstract string Environment { get; }
private string ClientId() =>
ClientOrderIds.Build(TradingRig.Installation, Environment, Strategies.CryptoTrend, OrderPurpose.Entry, ClientOrderIds.Key(new Guid("0193a7c0-0000-7000-8000-000000000031")), 1);
ClientOrderIds.Build(TradingRig.Installation, Environment, StrategyNames.CryptoTrend, OrderPurpose.Entry, ClientOrderIds.Key(new Guid("0193a7c0-0000-7000-8000-000000000031")), 1);
[TestMethod]
public async Task TheVenueAnswersWithItsTimeAndItsCash()
+23 -23
View File
@@ -17,7 +17,7 @@ public sealed class LedgerTests
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var account = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Simulation).ConfigureAwait(false);
var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")).ConfigureAwait(false);
const string strategy = Strategies.EquityMomentum;
const string strategy = StrategyNames.EquityMomentum;
await rig.Ledger.RecordCapitalAsync(account.AccountId, strategy, 10000m, "USD", "test", _none).ConfigureAwait(false);
var first = await rig.Ledger.RecordFillAsync(rig.Fill(account, msft, strategy, OrderSide.Buy, 10m, 400m, 0.03m) with { ReferencePrice = 399.8m }, _none).ConfigureAwait(false);
@@ -65,7 +65,7 @@ public sealed class LedgerTests
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false);
var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false);
const string strategy = Strategies.CryptoTrend;
const string strategy = StrategyNames.CryptoTrend;
await rig.Ledger.RecordCapitalAsync(account.AccountId, strategy, 5000m, "EUR", "test", _none).ConfigureAwait(false);
// OKX keeps the fee of a purchase in the bought coin (SPEC 4.2): 0.01 bought, 0.00001 kept.
@@ -99,14 +99,14 @@ public sealed class LedgerTests
var alpaca = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Simulation).ConfigureAwait(false);
var pepe = await rig.InstrumentAsync(TradingRig.Pepe).ConfigureAwait(false);
var aapl = await rig.InstrumentAsync(TradingRig.Stock("AAPL")).ConfigureAwait(false);
await rig.Ledger.RecordCapitalAsync(okx.AccountId, Strategies.CryptoTrend, 1000m, "EUR", "test", _none).ConfigureAwait(false);
await rig.Ledger.RecordCapitalAsync(alpaca.AccountId, Strategies.EquityMomentum, 3000m, "USD", "test", _none).ConfigureAwait(false);
await rig.Ledger.RecordCapitalAsync(okx.AccountId, StrategyNames.CryptoTrend, 1000m, "EUR", "test", _none).ConfigureAwait(false);
await rig.Ledger.RecordCapitalAsync(alpaca.AccountId, StrategyNames.EquityMomentum, 3000m, "USD", "test", _none).ConfigureAwait(false);
// A residue below the minimum is written off at market value as a cost: the trade closes (SPEC 7.2).
await rig.Ledger.RecordFillAsync(rig.Fill(okx, pepe, Strategies.CryptoTrend, OrderSide.Buy, 10_000_000m, 0.00001m), _none).ConfigureAwait(false);
await rig.Ledger.RecordFillAsync(rig.Fill(okx, pepe, Strategies.CryptoTrend, OrderSide.Sell, 9_950_000m, 0.000011m), _none).ConfigureAwait(false);
await rig.Ledger.WriteOffResidueAsync(okx.AccountId, pepe.Id, Strategies.CryptoTrend, 0.000011m, "below_minimum", _none).ConfigureAwait(false);
Assert.IsNull(await rig.Ledger.PositionAsync(okx.AccountId, pepe.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false));
await rig.Ledger.RecordFillAsync(rig.Fill(okx, pepe, StrategyNames.CryptoTrend, OrderSide.Buy, 10_000_000m, 0.00001m), _none).ConfigureAwait(false);
await rig.Ledger.RecordFillAsync(rig.Fill(okx, pepe, StrategyNames.CryptoTrend, OrderSide.Sell, 9_950_000m, 0.000011m), _none).ConfigureAwait(false);
await rig.Ledger.WriteOffResidueAsync(okx.AccountId, pepe.Id, StrategyNames.CryptoTrend, 0.000011m, "below_minimum", _none).ConfigureAwait(false);
Assert.IsNull(await rig.Ledger.PositionAsync(okx.AccountId, pepe.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false));
var residue = (await rig.QueryAsync("SELECT quantity, value FROM residues", r => (Q: r.Money("quantity"), V: r.Money("value"))).ConfigureAwait(false)).Single();
Assert.AreEqual((50_000m, 0.55m), (residue.Q, residue.V));
var trade = (await rig.QueryAsync("SELECT status, realized FROM trades WHERE instrument_id = @i", r => (S: r.Text("status"), R: r.Money("realized")), ("i", pepe.Id))
@@ -116,23 +116,23 @@ public sealed class LedgerTests
Assert.AreEqual(okxEquity.Result, trade.R, "The written-off value is a loss of the trade, nothing else.");
// A dividend goes to whoever held the stock before the ex-date.
await rig.Ledger.RecordFillAsync(rig.Fill(alpaca, aapl, Strategies.EquityMomentum, OrderSide.Buy, 10m, 200m), _none).ConfigureAwait(false);
await rig.Ledger.RecordFillAsync(rig.Fill(alpaca, aapl, StrategyNames.EquityMomentum, OrderSide.Buy, 10m, 200m), _none).ConfigureAwait(false);
rig.Clock.Advance(TimeSpan.FromDays(3));
Assert.AreEqual(10m, await rig.Ledger.QuantityAtAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, rig.Clock.UtcNow, _none).ConfigureAwait(false));
Assert.AreEqual(0m, await rig.Ledger.QuantityAtAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, TradingRig.Start.AddMinutes(-1), _none).ConfigureAwait(false));
await rig.Ledger.RecordDividendAsync(alpaca.AccountId, Strategies.EquityMomentum, 2.5m, "USD", rig.Clock.UtcNow, "Dividendo AAPL", _none).ConfigureAwait(false);
Assert.AreEqual(10m, await rig.Ledger.QuantityAtAsync(alpaca.AccountId, aapl.Id, StrategyNames.EquityMomentum, rig.Clock.UtcNow, _none).ConfigureAwait(false));
Assert.AreEqual(0m, await rig.Ledger.QuantityAtAsync(alpaca.AccountId, aapl.Id, StrategyNames.EquityMomentum, TradingRig.Start.AddMinutes(-1), _none).ConfigureAwait(false));
await rig.Ledger.RecordDividendAsync(alpaca.AccountId, StrategyNames.EquityMomentum, 2.5m, "USD", rig.Clock.UtcNow, "Dividendo AAPL", _none).ConfigureAwait(false);
// A 4-for-1 split: four times the shares at a quarter of the price, the value unchanged; applied once.
await rig.Ledger.SetStopAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, 180m, _none).ConfigureAwait(false);
await rig.Ledger.SetStopAsync(alpaca.AccountId, aapl.Id, StrategyNames.EquityMomentum, 180m, _none).ConfigureAwait(false);
var before = (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(e => e.AccountId == alpaca.AccountId);
// A split whose ex-date came before the purchase changes nothing: those shares were new shares already.
Assert.AreEqual(0m, await rig.Ledger.ApplySplitAsync(alpaca.AccountId, aapl.Id, "split-aapl-old", 2m, TradingRig.Start.AddDays(-30), _none).ConfigureAwait(false));
Assert.AreEqual(10m, (await rig.Ledger.PositionAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!.Quantity);
Assert.AreEqual(10m, (await rig.Ledger.PositionAsync(alpaca.AccountId, aapl.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.Quantity);
Assert.AreEqual(10m, await rig.Ledger.ApplySplitAsync(alpaca.AccountId, aapl.Id, "split-aapl-1", 4m, rig.Clock.UtcNow, _none).ConfigureAwait(false));
Assert.IsNull(await rig.Ledger.ApplySplitAsync(alpaca.AccountId, aapl.Id, "split-aapl-1", 4m, rig.Clock.UtcNow, _none).ConfigureAwait(false), "Never twice.");
var split = (await rig.Ledger.PositionAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!;
var split = (await rig.Ledger.PositionAsync(alpaca.AccountId, aapl.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!;
Assert.AreEqual((40m, 50m, 45m), (split.Quantity, split.AveragePrice, split.StopPrice));
Assert.AreEqual(40m, (await rig.Ledger.OpenLotsAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false)).Sum(l => l.Remaining));
Assert.AreEqual(40m, (await rig.Ledger.OpenLotsAsync(alpaca.AccountId, aapl.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false)).Sum(l => l.Remaining));
var after = (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(e => e.AccountId == alpaca.AccountId);
Assert.AreEqual(before.Equity, after.Equity);
Assert.AreEqual(3002.5m, after.Equity, "Capital, plus the dividend; the position at its own price.");
@@ -152,7 +152,7 @@ public sealed class LedgerTests
var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false);
var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false);
var eth = await rig.InstrumentAsync(MarketDataStoreTests.Okx("ETH-EUR")).ConfigureAwait(false);
const string strategy = Strategies.CryptoTrend;
const string strategy = StrategyNames.CryptoTrend;
await rig.Ledger.RecordCapitalAsync(account.AccountId, strategy, 100_000m, "EUR", "test", _none).ConfigureAwait(false);
var gen = new Gen(Property.DefaultSeed);
@@ -213,7 +213,7 @@ public sealed class LedgerTests
var alpaca = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Demo).ConfigureAwait(false);
await rig.Db.WriteAsync(async s =>
{
foreach (var (strategy, account, share) in new[] { (Strategies.CryptoTrend, okx, 1m), (Strategies.EquityMomentum, alpaca, 0.75m), (Strategies.EquityMeanrev, alpaca, 0.25m) })
foreach (var (strategy, account, share) in new[] { (StrategyNames.CryptoTrend, okx, 1m), (StrategyNames.EquityMomentum, alpaca, 0.75m), (StrategyNames.EquityMeanrev, alpaca, 0.25m) })
{
await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share) VALUES (@id, @s, @a, 'observation', 0, @j, @now, @now, @sh)",
_none, ("id", Ids.NewId(rig.Clock)), ("s", strategy), ("a", account.AccountId), ("j", new Anubis.Db.DbJson("{}")), ("now", rig.Clock.UtcNow), ("sh", share))
@@ -227,15 +227,15 @@ public sealed class LedgerTests
var alpacaCapital = await capital.SetAsync(Venues.Alpaca, 6000m, "test", _none).ConfigureAwait(false);
Assert.AreEqual(6600m, alpacaCapital.Amount);
var strategies = await capital.StrategiesAsync(Venues.Alpaca, _none).ConfigureAwait(false);
Assert.AreEqual(4950m, strategies.Single(s => s.Strategy == Strategies.EquityMomentum).Capital);
Assert.AreEqual(1650m, strategies.Single(s => s.Strategy == Strategies.EquityMeanrev).Capital);
Assert.AreEqual(4950m, strategies.Single(s => s.Strategy == StrategyNames.EquityMomentum).Capital);
Assert.AreEqual(1650m, strategies.Single(s => s.Strategy == StrategyNames.EquityMeanrev).Capital);
var book = new EquityBook(rig.Db, rig.Clock, rig.Ledger, fx);
await book.TakeAsync(_none).ConfigureAwait(false);
// A gain of 400 € on OKX, then the capital doubles: the return stays 10%, the deposit is no gain.
var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false);
await rig.Ledger.RecordFillAsync(rig.Fill(okx, btc, Strategies.CryptoTrend, OrderSide.Buy, 0.05m, 60000m), _none).ConfigureAwait(false);
await rig.Ledger.RecordFillAsync(rig.Fill(okx, btc, StrategyNames.CryptoTrend, OrderSide.Buy, 0.05m, 60000m), _none).ConfigureAwait(false);
await rig.Ledger.MarkAsync(btc.Id, 68000m, _none).ConfigureAwait(false);
rig.Clock.Advance(TimeSpan.FromMinutes(5));
await book.TakeAsync(_none).ConfigureAwait(false);
@@ -244,7 +244,7 @@ public sealed class LedgerTests
await book.TakeAsync(_none).ConfigureAwait(false);
var series = await rig.QueryAsync("SELECT equity, flows, twr_index, drawdown_pct FROM equity_snapshots WHERE scope = 'strategy' AND strategy = @s ORDER BY taken_at",
r => (E: r.Money("equity"), F: r.Money("flows"), I: r.Money("twr_index"), D: r.Money("drawdown_pct")), ("s", Strategies.CryptoTrend)).ConfigureAwait(false);
r => (E: r.Money("equity"), F: r.Money("flows"), I: r.Money("twr_index"), D: r.Money("drawdown_pct")), ("s", StrategyNames.CryptoTrend)).ConfigureAwait(false);
CollectionAssert.AreEqual(new[] { 4000m, 4400m, 8400m }, series.Select(p => p.E).ToArray());
Assert.AreEqual(1.1m, series[^1].I);
Assert.AreEqual(0.1m, Returns.TimeWeighted(series.Select(p => (p.E, p.F)).ToList()));
@@ -260,6 +260,6 @@ public sealed class LedgerTests
var error = await Assert.ThrowsExactlyAsync<CapitalException>(() => capital.SetAsync(Venues.Okx, 0m, "test", _none)).ConfigureAwait(false);
Assert.Contains("crypto_trend", error.Message);
await Assert.ThrowsExactlyAsync<CapitalException>(() =>
capital.SetSharesAsync(Venues.Alpaca, new Dictionary<string, decimal> { [Strategies.EquityMomentum] = 0.8m, [Strategies.EquityMeanrev] = 0.3m }, "test", _none)).ConfigureAwait(false);
capital.SetSharesAsync(Venues.Alpaca, new Dictionary<string, decimal> { [StrategyNames.EquityMomentum] = 0.8m, [StrategyNames.EquityMeanrev] = 0.3m }, "test", _none)).ConfigureAwait(false);
}
}
+19 -19
View File
@@ -38,10 +38,10 @@ public sealed class OrderManagerTests
return new Setup(rig, account, instrument, paper, rig.Manager(paper, account, pendingSplit: pendingSplit));
}
private static TradeIntent Buy(Setup s, decimal quantity, decimal? stop = null, bool aggressive = false, string strategy = Strategies.CryptoTrend) =>
private static TradeIntent Buy(Setup s, decimal quantity, decimal? stop = null, bool aggressive = false, string strategy = StrategyNames.CryptoTrend) =>
new(s.Instrument.Id, strategy, OrderSide.Buy, quantity, OrderPurpose.Entry, Ids.NewId(s.Rig.Clock)) { StopLevel = stop, StartAggressive = aggressive };
private static TradeIntent Sell(Setup s, decimal quantity, string strategy = Strategies.CryptoTrend) =>
private static TradeIntent Sell(Setup s, decimal quantity, string strategy = StrategyNames.CryptoTrend) =>
new(s.Instrument.Id, strategy, OrderSide.Sell, quantity, OrderPurpose.Exit, Ids.NewId(s.Rig.Clock));
private static Task<IReadOnlyList<(string Purpose, string Kind, string Status, decimal Quantity, decimal? Limit, decimal? Stop, bool PostOnly, string Tif, string ClientId)>> OrdersAsync(TradingRig rig) =>
@@ -75,7 +75,7 @@ public sealed class OrderManagerTests
CollectionAssert.AreEqual(new[] { ">created", "created>submitted", "submitted>canceled" }, events.ToArray(), "Every transition is recorded.");
// Held: 0.01 less the taker fee kept in coin. The slippage against the mid of the first order is measured.
var position = (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false))!;
var position = (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false))!;
Assert.AreEqual((0.00998m, 57000m), (position.Quantity, position.StopPrice));
var slippage = (await s.Rig.QueryAsync("SELECT slippage_bp FROM fills", r => r.Money("slippage_bp")).ConfigureAwait(false)).Single();
Assert.IsTrue(slippage is > 0m and < 10m, slippage.ToString(System.Globalization.CultureInfo.InvariantCulture));
@@ -98,7 +98,7 @@ public sealed class OrderManagerTests
var orders = await OrdersAsync(s.Rig).ConfigureAwait(false);
Assert.HasCount(4, orders);
Assert.IsTrue(orders.All(o => o.Status == "canceled"));
Assert.IsNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false));
Assert.IsNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false));
Assert.IsEmpty(await s.Paper.GetOpenOrdersAsync(_none).ConfigureAwait(false), "Nothing left working.");
}
@@ -109,7 +109,7 @@ public sealed class OrderManagerTests
await using var s = await OkxAsync().ConfigureAwait(false);
await s.Manager.SubmitAsync(Buy(s, 0.01m, stop: 40000m, aggressive: true), _none).ConfigureAwait(false);
await s.Rig.TurnsAsync(s.Manager, 2, _minute).ConfigureAwait(false);
var held = (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false))!.Quantity;
var held = (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false))!.Quantity;
// No price at all: the sale waits, and the stops stay on the broker until it can really leave.
s.Rig.QuotesDown = true;
@@ -151,12 +151,12 @@ public sealed class OrderManagerTests
}
TradeIntent BuyOf(Instrument coin, bool aggressive = false) =>
new(coin.Id, Strategies.CryptoTrend, OrderSide.Buy, 1m, OrderPurpose.Entry, Ids.NewId(s.Rig.Clock)) { StartAggressive = aggressive, StopLevel = 90m };
new(coin.Id, StrategyNames.CryptoTrend, OrderSide.Buy, 1m, OrderPurpose.Entry, Ids.NewId(s.Rig.Clock)) { StartAggressive = aggressive, StopLevel = 90m };
// A position to sell later.
await s.Manager.SubmitAsync(BuyOf(coins[8], aggressive: true), _none).ConfigureAwait(false);
await s.Rig.TurnsAsync(s.Manager, 2, TimeSpan.FromMinutes(2)).ConfigureAwait(false);
var held = (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, coins[8].Id, Strategies.CryptoTrend, _none).ConfigureAwait(false))!.Quantity;
var held = (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, coins[8].Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false))!.Quantity;
var buys = new List<Guid>();
foreach (var coin in coins.Take(8))
@@ -164,7 +164,7 @@ public sealed class OrderManagerTests
buys.Add((await s.Manager.SubmitAsync(BuyOf(coin), _none).ConfigureAwait(false)).Execution!.Value);
}
var sale = (await s.Manager.SubmitAsync(new TradeIntent(coins[8].Id, Strategies.CryptoTrend, OrderSide.Sell, held, OrderPurpose.Exit, Ids.NewId(s.Rig.Clock)), _none)
var sale = (await s.Manager.SubmitAsync(new TradeIntent(coins[8].Id, StrategyNames.CryptoTrend, OrderSide.Sell, held, OrderPurpose.Exit, Ids.NewId(s.Rig.Clock)), _none)
.ConfigureAwait(false)).Execution!.Value;
await s.Rig.TurnsAsync(s.Manager, 1, TimeSpan.FromSeconds(30)).ConfigureAwait(false);
@@ -193,7 +193,7 @@ public sealed class OrderManagerTests
public async Task AlpacaStopsAreGtcForWholeSharesAndDayForTheFractionAndFollowEveryChange()
{
await using var s = await AlpacaAsync().ConfigureAwait(false);
await s.Manager.SubmitAsync(Buy(s, 10.5m, stop: 380m, aggressive: true, strategy: Strategies.EquityMomentum), _none).ConfigureAwait(false);
await s.Manager.SubmitAsync(Buy(s, 10.5m, stop: 380m, aggressive: true, strategy: StrategyNames.EquityMomentum), _none).ConfigureAwait(false);
await s.Rig.TurnsAsync(s.Manager, 2, _minute).ConfigureAwait(false);
var stops = (await OrdersAsync(s.Rig).ConfigureAwait(false)).Where(o => o.Purpose == "stop" && o.Status == "submitted").OrderBy(o => o.Quantity).ToList();
Assert.AreEqual(2, stops.Count);
@@ -202,7 +202,7 @@ public sealed class OrderManagerTests
Assert.IsTrue(stops.All(o => o.Stop == 380m && o.Kind == "stop"));
// Adding to the position: Alpaca refuses a buy with a sell stop open, so the stops leave, the buy goes, they come back.
await s.Manager.SubmitAsync(Buy(s, 5m, aggressive: true, strategy: Strategies.EquityMomentum), _none).ConfigureAwait(false);
await s.Manager.SubmitAsync(Buy(s, 5m, aggressive: true, strategy: StrategyNames.EquityMomentum), _none).ConfigureAwait(false);
await s.Rig.TurnsAsync(s.Manager, 2, _minute).ConfigureAwait(false);
var all = await OrdersAsync(s.Rig).ConfigureAwait(false);
Assert.IsTrue(stops.All(old => all.Single(o => o.ClientId == old.ClientId).Status == "canceled"));
@@ -215,7 +215,7 @@ public sealed class OrderManagerTests
s.Rig.Quote("MSFT", 379m, 379.20m);
await s.Paper.PumpAsync(_none).ConfigureAwait(false);
await s.Rig.TurnsAsync(s.Manager, 3, _minute).ConfigureAwait(false);
Assert.IsNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false));
Assert.IsNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false));
var protective = (await OrdersAsync(s.Rig).ConfigureAwait(false)).Single(o => o.Purpose == "protective");
Assert.AreEqual(("market", 0.5m, "filled"), (protective.Kind, protective.Quantity, protective.Status));
Assert.AreEqual("stop", (await s.Rig.QueryAsync("SELECT exit_reason FROM trades", r => r.Text("exit_reason")).ConfigureAwait(false)).Single());
@@ -231,9 +231,9 @@ public sealed class OrderManagerTests
await s.Rig.TurnsAsync(s.Manager, 2, _minute).ConfigureAwait(false);
// The level to place is already above the price: the stop counts as fired (SPEC 7.2).
await s.Rig.Ledger.SetStopAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, 61000m, _none).ConfigureAwait(false);
await s.Rig.Ledger.SetStopAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, 61000m, _none).ConfigureAwait(false);
await s.Rig.TurnsAsync(s.Manager, 3, _minute).ConfigureAwait(false);
Assert.IsNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false));
Assert.IsNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false));
Assert.AreEqual("market", (await OrdersAsync(s.Rig).ConfigureAwait(false)).Single(o => o.Purpose == "protective").Kind);
Assert.AreEqual("stop", (await s.Rig.QueryAsync("SELECT exit_reason FROM trades", r => r.Text("exit_reason")).ConfigureAwait(false)).Single());
Assert.HasCount(1, await s.Rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'stop_already_passed'", r => r.Id("id")).ConfigureAwait(false));
@@ -248,15 +248,15 @@ public sealed class OrderManagerTests
applied = true;
return Task.FromResult(first ? new CorporateAction(instrument.Symbol, CorporateActionKinds.Split, new DateOnly(2026, 11, 11), "test", "split-msft") { Ratio = 4m } : null);
}).ConfigureAwait(false);
await a.Manager.SubmitAsync(Buy(a, 10m, aggressive: true, strategy: Strategies.EquityMomentum), _none).ConfigureAwait(false);
await a.Manager.SubmitAsync(Buy(a, 10m, aggressive: true, strategy: StrategyNames.EquityMomentum), _none).ConfigureAwait(false);
await a.Rig.TurnsAsync(a.Manager, 2, _minute).ConfigureAwait(false);
a.Rig.Clock.Advance(TimeSpan.FromDays(1));
a.Rig.Quote("MSFT", 100m, 100.05m);
await a.Rig.Ledger.SetStopAsync(a.Account.AccountId, a.Instrument.Id, Strategies.EquityMomentum, 380m, _none).ConfigureAwait(false);
await a.Rig.Ledger.SetStopAsync(a.Account.AccountId, a.Instrument.Id, StrategyNames.EquityMomentum, 380m, _none).ConfigureAwait(false);
await a.Rig.TurnsAsync(a.Manager, 2, _minute).ConfigureAwait(false);
Assert.IsTrue(applied);
var position = (await a.Rig.Ledger.PositionAsync(a.Account.AccountId, a.Instrument.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!;
var position = (await a.Rig.Ledger.PositionAsync(a.Account.AccountId, a.Instrument.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!;
Assert.AreEqual((40m, 95m), (position.Quantity, position.StopPrice));
Assert.IsFalse((await OrdersAsync(a.Rig).ConfigureAwait(false)).Any(o => o.Purpose == "protective"));
var stop = (await OrdersAsync(a.Rig).ConfigureAwait(false)).Single(o => o.Purpose == "stop" && o.Status == "submitted");
@@ -282,7 +282,7 @@ public sealed class OrderManagerTests
Assert.HasCount(1, faulty.Sent.Where(r => r.ClientOrderId == lost.ClientId).ToList(), "Sent once.");
Assert.AreEqual("done/filled", await ExecutionStatusAsync(s.Rig, execution!.Value).ConfigureAwait(false));
Assert.HasCount(1, await s.Rig.QueryAsync("SELECT id FROM fills", r => r.Id("id")).ConfigureAwait(false), "Every fill was reported twice, recorded once.");
Assert.AreEqual(0.00998m, (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false))!.Quantity);
Assert.AreEqual(0.00998m, (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false))!.Quantity);
// A refused buy ends, with its reason in the diary.
faulty.RejectNext = "insufficient";
@@ -305,14 +305,14 @@ public sealed class OrderManagerTests
await using var s = await OkxAsync(TradingRig.Pepe, bid: 0.00001m, ask: 0.00001001m).ConfigureAwait(false);
await s.Manager.SubmitAsync(Buy(s, 10_000_000m, aggressive: true), _none).ConfigureAwait(false);
await s.Rig.TurnsAsync(s.Manager, 2, _minute).ConfigureAwait(false);
var held = (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false))!.Quantity;
var held = (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false))!.Quantity;
Assert.AreEqual(9_980_000m, held);
s.Rig.Quote("PEPE-EUR", 0.0000099m, 0.00000991m);
var (execution, _) = await s.Manager.SubmitAsync(Sell(s, 9_900_000m) with { StartAggressive = true }, _none).ConfigureAwait(false);
await s.Rig.TurnsAsync(s.Manager, 3, _minute).ConfigureAwait(false);
Assert.AreEqual("done/filled", await ExecutionStatusAsync(s.Rig, execution!.Value).ConfigureAwait(false));
Assert.IsNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false));
Assert.IsNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false));
var residue = (await s.Rig.QueryAsync("SELECT quantity, reason FROM residues", r => (Q: r.Money("quantity"), R: r.Text("reason"))).ConfigureAwait(false)).Single();
Assert.AreEqual((80_000m, "below_minimum"), (residue.Q, residue.R));
Assert.AreEqual(("closed", "residue"), (await s.Rig.QueryAsync("SELECT status, exit_reason FROM trades", r => (r.Text("status"), r.Text("exit_reason"))).ConfigureAwait(false)).Single());
+8
View File
@@ -69,6 +69,14 @@ internal sealed class Gen(int seed)
/// <summary>Uniform value in [0, 1).</summary>
public double Double() => (NextUInt64() >> 11) * (1.0 / (1UL << 53));
/// <summary>A standard normal value (Box–Muller), for synthetic price series and returns.</summary>
public double Normal()
{
var u = 1.0 - Double();
var v = Double();
return Math.Sqrt(-2.0 * Math.Log(u)) * Math.Cos(2.0 * Math.PI * v);
}
/// <summary>A decimal in [<paramref name="min"/>, <paramref name="max"/>] with at most <paramref name="scale"/> decimals.</summary>
public decimal Decimal(decimal min, decimal max, int scale)
{
+7 -7
View File
@@ -25,11 +25,11 @@ public sealed class ReconcilerTests
var instrument = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false);
var paper = rig.Paper(PaperOptions.Okx(), account.AccountId);
await paper.DepositAsync(100_000m, "EUR", _none).ConfigureAwait(false);
await rig.Ledger.RecordCapitalAsync(account.AccountId, Strategies.CryptoTrend, 10_000m, "EUR", "test", _none).ConfigureAwait(false);
await rig.Ledger.RecordCapitalAsync(account.AccountId, StrategyNames.CryptoTrend, 10_000m, "EUR", "test", _none).ConfigureAwait(false);
rig.Quote(instrument.Symbol, 60000m, 60010m);
var broker = new FaultyBroker(paper, environment);
var manager = rig.Manager(broker, account);
await manager.SubmitAsync(new TradeIntent(instrument.Id, Strategies.CryptoTrend, OrderSide.Buy, 0.01m, OrderPurpose.Entry, Ids.NewId(rig.Clock))
await manager.SubmitAsync(new TradeIntent(instrument.Id, StrategyNames.CryptoTrend, OrderSide.Buy, 0.01m, OrderPurpose.Entry, Ids.NewId(rig.Clock))
{
StopLevel = 57000m,
StartAggressive = true,
@@ -52,7 +52,7 @@ public sealed class ReconcilerTests
private static Task<IReadOnlyList<string>> CodesAsync(TradingRig rig, string code) =>
rig.QueryAsync("SELECT code FROM journal WHERE code = @c", r => r.Text("code"), ("c", code));
private static TradeIntent Entry(Setup s) => new(s.Instrument.Id, Strategies.CryptoTrend, OrderSide.Buy, 0.001m, OrderPurpose.Entry, Ids.NewId(s.Rig.Clock));
private static TradeIntent Entry(Setup s) => new(s.Instrument.Id, StrategyNames.CryptoTrend, OrderSide.Buy, 0.001m, OrderPurpose.Entry, Ids.NewId(s.Rig.Clock));
[TestMethod]
[TestCategory(Category.Simulation)]
@@ -77,11 +77,11 @@ public sealed class ReconcilerTests
s.Rig.Quote("BTC-EUR", 56000m, 56010m);
await s.Paper.PumpAsync(_none).ConfigureAwait(false);
Assert.IsEmpty(await s.Paper.GetPositionsAsync(_none).ConfigureAwait(false));
Assert.IsNotNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false));
Assert.IsNotNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false));
var report = await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false);
Assert.AreEqual((ReconcileOutcomes.Healed, AccountModes.Normal), (report.Outcome, report.Mode), string.Join("; ", report.Differences.Select(d => d.Message)));
Assert.IsNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false));
Assert.IsNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false));
Assert.AreEqual("stop", (await s.Rig.QueryAsync("SELECT exit_reason FROM trades", r => r.Text("exit_reason")).ConfigureAwait(false)).Single());
Assert.HasCount(1, await CodesAsync(s.Rig, "reconcile_healed").ConfigureAwait(false));
Assert.HasCount(1, await s.Rig.QueryAsync("SELECT id FROM reconciliations WHERE outcome = 'healed'", r => r.Id("id")).ConfigureAwait(false));
@@ -132,7 +132,7 @@ public sealed class ReconcilerTests
// Align: the ledger takes the account's number with an adjustment, and the account is normal again.
await s.Reconciler.ResolveAsync(s.Manager, ReconcileChoice.Align, "test", _none).ConfigureAwait(false);
Assert.AreEqual(0.00598m, (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false))!.Quantity);
Assert.AreEqual(0.00598m, (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, StrategyNames.CryptoTrend, _none).ConfigureAwait(false))!.Quantity);
state = await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false);
Assert.AreEqual((AccountModes.Normal, ReconcileOutcomes.UserAligned), (state.Mode, state.LastOutcome));
Assert.HasCount(1, await CodesAsync(s.Rig, "account_resolved").ConfigureAwait(false));
@@ -148,7 +148,7 @@ public sealed class ReconcilerTests
public async Task AnUnknownOrderOfThisInstallationIsReportedAndCanBeLeftOut()
{
await using var s = await HoldingAsync().ConfigureAwait(false);
var stray = ClientOrderIds.Build(TradingRig.Installation, TradingEnvironments.Demo, Strategies.CryptoTrend, OrderPurpose.Entry, ClientOrderIds.Key(Guid.NewGuid()), 1);
var stray = ClientOrderIds.Build(TradingRig.Installation, TradingEnvironments.Demo, StrategyNames.CryptoTrend, OrderPurpose.Entry, ClientOrderIds.Key(Guid.NewGuid()), 1);
await s.Paper.SubmitOrderAsync(new OrderRequest(stray, "BTC-EUR", OrderSide.Buy, OrderKind.Limit, 0.001m, TimeInForce.Gtc) { LimitPrice = 50000m }, _none).ConfigureAwait(false);
// Someone else's order on the same account is none of the bot's business.
+4 -4
View File
@@ -22,7 +22,7 @@ public sealed class TradingRulesTests
Assert.AreEqual(installation, ClientOrderIds.InstallationCode(Guid.Parse("0193a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b")));
Assert.AreEqual(key, ClientOrderIds.Key(Guid.Parse("0193a1b2-0000-7000-8000-000000000001")));
var id = ClientOrderIds.Build(installation, TradingEnvironments.Demo, Strategies.EquityMomentum, OrderPurpose.Stop, key, 1297);
var id = ClientOrderIds.Build(installation, TradingEnvironments.Demo, StrategyNames.EquityMomentum, OrderPurpose.Stop, key, 1297);
Assert.AreEqual(ClientOrderIds.Length, id.Length);
Assert.IsLessThanOrEqualTo(32, id.Length);
Assert.IsTrue(id.StartsWith("ANU", StringComparison.Ordinal));
@@ -31,16 +31,16 @@ public sealed class TradingRulesTests
// From the id alone: strategy, environment, purpose and progressive (SPEC 7.2, 15.1).
var parts = ClientOrderIds.Parse(id);
Assert.IsNotNull(parts);
Assert.AreEqual(new ClientOrderIdParts(installation, TradingEnvironments.Demo, Strategies.EquityMomentum, OrderPurpose.Stop, key, 1297), parts);
Assert.AreEqual(new ClientOrderIdParts(installation, TradingEnvironments.Demo, StrategyNames.EquityMomentum, OrderPurpose.Stop, key, 1297), parts);
Assert.IsTrue(ClientOrderIds.IsOurs(id, installation));
Assert.IsFalse(ClientOrderIds.IsOurs(id, "ZZZZ"), "Another installation's order is not ours.");
Assert.IsFalse(ClientOrderIds.IsOurs("my-own-order-123", installation), "The user's own orders are never touched.");
Assert.IsNull(ClientOrderIds.Parse(null));
// Every progressive gives a different id; the next one is a different order.
Assert.AreNotEqual(id, ClientOrderIds.Build(installation, TradingEnvironments.Demo, Strategies.EquityMomentum, OrderPurpose.Stop, key, 1298));
Assert.AreNotEqual(id, ClientOrderIds.Build(installation, TradingEnvironments.Demo, StrategyNames.EquityMomentum, OrderPurpose.Stop, key, 1298));
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() =>
ClientOrderIds.Build(installation, TradingEnvironments.Demo, Strategies.CryptoTrend, OrderPurpose.Entry, key, ClientOrderIds.MaxSequence + 1));
ClientOrderIds.Build(installation, TradingEnvironments.Demo, StrategyNames.CryptoTrend, OrderPurpose.Entry, key, ClientOrderIds.MaxSequence + 1));
Assert.ThrowsExactly<ArgumentException>(() => ClientOrderIds.Build(installation, TradingEnvironments.Demo, "unknown", OrderPurpose.Entry, key, 1));
}
+14 -14
View File
@@ -36,9 +36,9 @@ public sealed class TradingServiceTests
// Every strategy starts in observation, crypto on OKX and stocks on Alpaca.
CollectionAssert.AreEqual(new[]
{
(Strategies.CryptoTrend, "OKX simulatore", Strategies.Observation),
(Strategies.EquityMeanrev, "Alpaca simulatore", Strategies.Observation),
(Strategies.EquityMomentum, "Alpaca simulatore", Strategies.Observation),
(StrategyNames.CryptoTrend, "OKX simulatore", StrategyNames.Observation),
(StrategyNames.EquityMeanrev, "Alpaca simulatore", StrategyNames.Observation),
(StrategyNames.EquityMomentum, "Alpaca simulatore", StrategyNames.Observation),
}, (await StrategiesAsync(rig).ConfigureAwait(false)).ToArray());
// A second start finds what is there.
@@ -55,16 +55,16 @@ public sealed class TradingServiceTests
await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var accounts = await AccountSetup.EnsureAsync(rig.Db, rig.Clock, alpacaDemo: false, okxDemo: false, _none).ConfigureAwait(false);
var simulator = accounts.Single(a => a.Broker == Venues.Alpaca);
await rig.Ledger.RecordCapitalAsync(simulator.AccountId, Strategies.EquityMeanrev, 500m, "USD", "test", _none).ConfigureAwait(false);
await rig.Ledger.RecordCapitalAsync(simulator.AccountId, StrategyNames.EquityMeanrev, 500m, "USD", "test", _none).ConfigureAwait(false);
accounts = await AccountSetup.EnsureAsync(rig.Db, rig.Clock, alpacaDemo: true, okxDemo: false, _none).ConfigureAwait(false);
Assert.HasCount(3, accounts);
Assert.IsFalse(accounts.Any(a => a.Environment == TradingEnvironments.Live), "Never a real account in this phase (SPEC 2.2).");
CollectionAssert.AreEqual(new[]
{
(Strategies.CryptoTrend, "OKX simulatore", Strategies.Observation),
(Strategies.EquityMeanrev, "Alpaca simulatore", Strategies.Observation),
(Strategies.EquityMomentum, "Alpaca paper", Strategies.Observation),
(StrategyNames.CryptoTrend, "OKX simulatore", StrategyNames.Observation),
(StrategyNames.EquityMeanrev, "Alpaca simulatore", StrategyNames.Observation),
(StrategyNames.EquityMomentum, "Alpaca paper", StrategyNames.Observation),
}, (await StrategiesAsync(rig).ConfigureAwait(false)).ToArray(), "A strategy with a history stays where it is.");
}
@@ -91,7 +91,7 @@ public sealed class TradingServiceTests
Assert.AreEqual(1000m, await BookAsync(Venues.Okx, "EUR").ConfigureAwait(false));
Assert.AreEqual(2200m, await BookAsync(Venues.Alpaca, "USD").ConfigureAwait(false), "Funded once, not again at every call.");
var shares = await rig.QueryAsync("SELECT strategy, capital FROM strategy_state ORDER BY strategy", r => (r.Text("strategy"), r.Money("capital"))).ConfigureAwait(false);
CollectionAssert.AreEqual(new[] { (Strategies.CryptoTrend, 1000m), (Strategies.EquityMeanrev, 550m), (Strategies.EquityMomentum, 1650m) }, shares.ToArray());
CollectionAssert.AreEqual(new[] { (StrategyNames.CryptoTrend, 1000m), (StrategyNames.EquityMeanrev, 550m), (StrategyNames.EquityMomentum, 1650m) }, shares.ToArray());
// The dollar falls: saving the same euro again changes nothing, and only a new euro amount is converted at today's rate.
await new FxStore(rig.Db, rig.Clock).UpsertAsync([new FxRate("EUR", "USD", new DateOnly(2026, 11, 10), 1.05m, "ecb")], _none).ConfigureAwait(false);
@@ -110,8 +110,8 @@ public sealed class TradingServiceTests
var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")).ConfigureAwait(false);
await service.StartAsync(_none).ConfigureAwait(false);
var account = service.Managers.Single(m => m.Account.Broker == Venues.Alpaca).Account;
await service.Ledger.RecordCapitalAsync(account.AccountId, Strategies.EquityMomentum, 5000m, "USD", "test", _none).ConfigureAwait(false);
await service.Ledger.RecordFillAsync(rig.Fill(account, msft, Strategies.EquityMomentum, OrderSide.Buy, 10m, 400m, feeCurrency: "USD"), _none).ConfigureAwait(false);
await service.Ledger.RecordCapitalAsync(account.AccountId, StrategyNames.EquityMomentum, 5000m, "USD", "test", _none).ConfigureAwait(false);
await service.Ledger.RecordFillAsync(rig.Fill(account, msft, StrategyNames.EquityMomentum, OrderSide.Buy, 10m, 400m, feeCurrency: "USD"), _none).ConfigureAwait(false);
// Bought on Tuesday; Wednesday is the ex-date of 0,75 USD a share; Thursday a 2-for-1 split. A split of last
// month is still in the table: it came before the purchase and must change nothing.
@@ -129,18 +129,18 @@ public sealed class TradingServiceTests
await service.CorporateActionsAsync(_none).ConfigureAwait(false);
Assert.IsEmpty(await DividendsAsync().ConfigureAwait(false), "Nothing before the ex-date.");
Assert.AreEqual(10m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!.Quantity, "An old split is not applied to new shares.");
Assert.AreEqual(10m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.Quantity, "An old split is not applied to new shares.");
rig.Clock.Advance(TimeSpan.FromDays(1));
await service.CorporateActionsAsync(_none).ConfigureAwait(false);
await service.CorporateActionsAsync(_none).ConfigureAwait(false);
CollectionAssert.AreEqual(new[] { 7.5m }, (await DividendsAsync().ConfigureAwait(false)).ToArray());
Assert.AreEqual(10m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!.Quantity);
Assert.AreEqual(10m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.Quantity);
rig.Clock.Advance(TimeSpan.FromDays(1));
await service.CorporateActionsAsync(_none).ConfigureAwait(false);
await service.CorporateActionsAsync(_none).ConfigureAwait(false);
var position = (await service.Ledger.PositionAsync(account.AccountId, msft.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!;
var position = (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!;
Assert.AreEqual((20m, 200m), (position.Quantity, position.AveragePrice));
Assert.HasCount(1, await DividendsAsync().ConfigureAwait(false));
Assert.HasCount(1, await rig.QueryAsync("SELECT code FROM journal WHERE code = 'split_applied'", r => r.Text("code")).ConfigureAwait(false));
@@ -149,6 +149,6 @@ public sealed class TradingServiceTests
// Every photograph values the positions at the market, not at their last fill.
service.Quotes.Put(new Quote("MSFT", 230m, 230.10m, rig.Clock.UtcNow));
await service.PhotographAsync(_none).ConfigureAwait(false);
Assert.AreEqual(230.05m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!.LastPrice);
Assert.AreEqual(230.05m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, StrategyNames.EquityMomentum, _none).ConfigureAwait(false))!.LastPrice);
}
}
+1 -1
View File
@@ -46,7 +46,7 @@ internal sealed class TradingRig : IAsyncDisposable
public async Task<AccountContext> AccountAsync(string broker, string environment, string? name = null)
{
var account = new AccountContext(Ids.NewId(Clock), name ?? AccountSetup.NameOf(broker, environment), broker, environment, Strategies.CurrencyOf(broker));
var account = new AccountContext(Ids.NewId(Clock), name ?? AccountSetup.NameOf(broker, environment), broker, environment, StrategyNames.CurrencyOf(broker));
await Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, @n, @b, @e, @c, @now)", CancellationToken.None,
("id", account.AccountId), ("n", account.Name), ("b", broker), ("e", environment), ("c", account.Currency), ("now", Clock.UtcNow)), CancellationToken.None).ConfigureAwait(false);
return account;