using Anubis.Core;
using Anubis.Data;
using Anubis.Trading;
namespace Anubis.Tests;
/// The live engine in simulation (issue #47, SPEC 5.5, 5.6, 12.3, 17 phase 6).
[TestClass]
public sealed class LiveEngineTests
{
private static readonly DateOnly LiveFrom = new(2026, 9, 1);
[TestMethod]
public async Task TheLiveEngineMakesTheSameTradesAsTheBacktest()
{
var last = LiveFrom.AddDays(39);
await using var live = await LiveRig.CreateAsync(LiveFrom, last).ConfigureAwait(false);
for (var day = LiveFrom; day <= last; day = day.AddDays(1))
{
await live.DayAsync(day).ConfigureAwait(false);
}
// The backtest decides on the close of the day before the first live morning and fills on the live days, with
// the same correctives (crypto regime) and the same risk stage.
var expected = LiveRig.Grouped(live.Backtest(LiveFrom.AddDays(-1), last), LiveFrom);
Assert.IsGreaterThanOrEqualTo(8, expected.Count, "The synthetic path should make the backtest trade: " + expected.Count);
LiveRig.AssertSameTrades(expected, await live.LiveFillsAsync().ConfigureAwait(false));
// Every decision was written once, with its run key.
var runs = await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false);
Assert.HasCount(runs.Distinct(StringComparer.Ordinal).Count(), runs);
Assert.HasCount(40, runs);
Assert.AreEqual(0, live.Failures);
}
///
/// The stock side (SPEC 5.5): equity_meanrev decides after the close, buys at the next open, leaves five minutes
/// before the close; the trades are the backtest's, which buys at the open and sells at the close.
///
[TestMethod]
public async Task TheStockSideMakesTheSameTradesAsTheBacktest()
{
var last = LiveFrom.AddDays(41);
await using var live = await StockRig.CreateAsync(LiveFrom, last).ConfigureAwait(false);
for (var day = LiveFrom; day <= last; day = day.AddDays(1))
{
await live.SessionAsync(day).ConfigureAwait(false);
}
var run = live.Backtest(StrategyNames.EquityMeanrev, LiveFrom.AddDays(-1), last);
var expected = LiveRig.Grouped(run, LiveFrom);
Assert.IsGreaterThanOrEqualTo(8, expected.Count, "The synthetic stocks should make the backtest trade: " + expected.Count);
LiveRig.AssertSameTrades(expected, await live.LiveFillsAsync().ConfigureAwait(false));
// One decision per session, each written once: the close of the day before the first one included, made at the
// first start as a recovered decision.
var runs = await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false);
Assert.HasCount(runs.Distinct(StringComparer.Ordinal).Count(), runs);
var sessions = WeekdayCalendar.Sessions(LiveFrom.AddDays(-1), last).Count();
Assert.HasCount(sessions, runs.Where(r => r.StartsWith(StrategyNames.EquityMeanrev + ":", StringComparison.Ordinal)).ToList());
}
///
/// SPEC 17 phase 6: an accelerated run of at least 10 market days with faults injected (network, a restart
/// halfway through an order, the database unreachable) ends with ledger and account reconciled and no order sent
/// twice; the trades are still the backtest's.
///
[TestMethod]
public async Task TenDaysWithFaultsEndReconciledWithoutDuplicateOrders()
{
var last = LiveFrom.AddDays(13);
await using var live = await LiveRig.CreateAsync(LiveFrom, last).ConfigureAwait(false);
var restarted = false;
var waited = false;
(int Runs, int Sent) before = default;
for (var day = LiveFrom; day <= last; day = day.AddDays(1))
{
var index = day.DayNumber - LiveFrom.DayNumber;
Func? faults = index switch
{
// Network down for the first minutes of the decision: no quotes, no broker. When it comes back, the
// answer to the first order is lost on the way back.
0 => minute =>
{
live.Rig.QuotesDown = live.Broker.Down = minute < 4;
if (minute == 4)
{
live.Broker.LoseNextAnswer = true;
}
return Task.CompletedTask;
}
,
// The account has not finished its startup (the broker did not answer it): for three minutes nothing is
// decided or sent on it, then the decision is made late.
5 => async minute =>
{
var runs = (await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false)).Count;
if (minute == 0)
{
before = (runs, live.Sent.Count);
}
else if (minute == 3)
{
Assert.AreEqual(before, (runs, live.Sent.Count), "Nothing is decided or sent on an account not started.");
waited = true;
}
live.AccountStarted = minute >= 3;
}
,
// The process dies with a purchase working at the broker and starts again.
11 => async minute =>
{
if (!restarted && await live.WorkingOrdersAsync().ConfigureAwait(false) > 0)
{
restarted = true;
await live.RestartAsync().ConfigureAwait(false);
}
}
,
// The database cannot be reached around the decision.
12 => minute =>
{
live.DatabaseDown = minute < 6;
return Task.CompletedTask;
}
,
_ => null,
};
await live.DayAsync(day, faults).ConfigureAwait(false);
if (index == 0)
{
Assert.IsFalse(live.Broker.LoseNextAnswer, "An answer must have been lost.");
}
}
Assert.IsTrue(restarted, "The run must restart halfway through an order.");
Assert.IsTrue(waited, "The run must hold an account not started.");
Assert.AreEqual(1, live.Restarts);
Assert.IsGreaterThan(0, live.Failures, "The faults must have hit the work.");
// The trades are the backtest's: the faults delayed them by minutes, never changed or repeated them.
var expected = LiveRig.Grouped(live.Backtest(LiveFrom.AddDays(-1), last), LiveFrom);
LiveRig.AssertSameTrades(expected, await live.LiveFillsAsync().ConfigureAwait(false));
// No order twice: one order per client id, one execution per order key, one decision per run key.
var orders = await live.Rig.QueryAsync("SELECT client_order_id FROM orders", r => r.Text("client_order_id")).ConfigureAwait(false);
Assert.HasCount(orders.Distinct(StringComparer.Ordinal).Count(), orders);
foreach (var id in live.Sent.Select(r => r.ClientOrderId).Distinct(StringComparer.Ordinal))
{
Assert.Contains(id, orders, "Every order sent is in the ledger.");
}
var keys = await live.Rig.QueryAsync("SELECT order_key FROM executions", r => r.Text("order_key")).ConfigureAwait(false);
Assert.HasCount(keys.Distinct(StringComparer.Ordinal).Count(), keys);
var runs = await live.Rig.QueryAsync("SELECT run_key FROM engine_runs", r => r.Text("run_key")).ConfigureAwait(false);
Assert.HasCount(14, runs.Distinct(StringComparer.Ordinal));
Assert.HasCount(14, runs);
// Ledger and account agree; the account may keep dust below the lot that the ledger wrote off (SPEC 7.2).
var report = await live.Reconciler.ReconcileAsync(live.Manager, CancellationToken.None).ConfigureAwait(false);
Assert.AreEqual(ReconcileOutcomes.Clean, report.Outcome, string.Join("; ", report.Differences));
var ledger = (await live.Rig.Ledger.PositionsAsync(live.Okx.AccountId, CancellationToken.None).ConfigureAwait(false))
.Where(p => p.Quantity != 0m)
.GroupBy(p => p.InstrumentId).ToDictionary(g => live.Instruments.Values.Single(i => i.Id == g.Key).Symbol, g => g.Sum(p => p.Quantity), StringComparer.Ordinal);
var account = (await live.Paper.GetPositionsAsync(CancellationToken.None).ConfigureAwait(false)).Where(p => p.Quantity != 0m)
.ToDictionary(p => p.Symbol, p => p.Quantity, StringComparer.Ordinal);
CollectionAssert.AreEquivalent(account.Where(a => a.Value >= (live.Instruments[a.Key].Spec.LotSize ?? 0m)).Select(a => a.Key).ToList(), ledger.Keys.ToList());
foreach (var (symbol, quantity) in account.Where(a => ledger.ContainsKey(a.Key)))
{
Assert.IsLessThan(live.Instruments[symbol].Spec.LotSize ?? 0m, Math.Abs(quantity - ledger[symbol]), symbol);
}
}
}