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
@@ -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());
|
||||
|
||||
Reference in new issue
Block a user