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:
1 parent
6d3ef8e7b5
commit
d97304d7b9
19 files changed
+1592
-78
No files matched your search
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user