Files
Anubis/tests/Anubis.Tests/OrderManagerTests.cs
Alby96andClaude Opus 5.5 d97304d7b9 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>
2026-11-11 09:29:01 +01:00

323 lines
24 KiB
C#

using Anubis.Core;
using Anubis.Data;
using Anubis.Trading;
namespace Anubis.Tests;
/// <summary>The order manager (issues #27, #28, #30, SPEC 7.2): chasing limit, pace, sales, server stops, faults.</summary>
[TestClass]
public sealed class OrderManagerTests
{
private static readonly CancellationToken _none = CancellationToken.None;
private static readonly TimeSpan _minute = TimeSpan.FromSeconds(60);
private sealed record Setup(TradingRig Rig, AccountContext Account, Instrument Instrument, PaperBroker Paper, OrderManager Manager) : IAsyncDisposable
{
public ValueTask DisposeAsync() => Rig.DisposeAsync();
}
private static async Task<Setup> OkxAsync(InstrumentSpec? spec = null, decimal bid = 60000m, decimal ask = 60010m)
{
var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false);
var instrument = await rig.InstrumentAsync(spec ?? TradingRig.Btc).ConfigureAwait(false);
var paper = rig.Paper(PaperOptions.Okx(), account.AccountId);
await paper.DepositAsync(100_000m, "EUR", _none).ConfigureAwait(false);
rig.Quote(instrument.Symbol, bid, ask);
return new Setup(rig, account, instrument, paper, rig.Manager(paper, account));
}
private static async Task<Setup> AlpacaAsync(Func<Instrument, CancellationToken, Task<CorporateAction?>>? pendingSplit = null)
{
var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
var account = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Simulation).ConfigureAwait(false);
var instrument = await rig.InstrumentAsync(TradingRig.Stock("MSFT")).ConfigureAwait(false);
var paper = rig.Paper(PaperOptions.Alpaca(), account.AccountId);
await paper.DepositAsync(50_000m, "USD", _none).ConfigureAwait(false);
rig.Quote(instrument.Symbol, 400m, 400.10m);
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 = 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 = 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) =>
rig.QueryAsync("SELECT purpose, order_type, status, quantity, limit_price, stop_price, post_only, time_in_force, client_order_id FROM orders ORDER BY created_at, id",
r => (r.Text("purpose"), r.Text("order_type"), r.Text("status"), r.Money("quantity"), r.MoneyOrNull("limit_price"), r.MoneyOrNull("stop_price"), r.Bool("post_only"),
r.Text("time_in_force"), r.Text("client_order_id")));
private static async Task<string> ExecutionStatusAsync(TradingRig rig, Guid id) =>
(await rig.QueryAsync("SELECT status, reason FROM executions WHERE id = @id", r => r.Text("status") + "/" + r.TextOrNull("reason"), ("id", id)).ConfigureAwait(false)).Single();
[TestMethod]
[TestCategory(Category.Simulation)]
public async Task ABuyChasesThePriceThenCrossesWithinToleranceAndGetsItsServerStop()
{
await using var s = await OkxAsync().ConfigureAwait(false);
var (execution, refusal) = await s.Manager.SubmitAsync(Buy(s, 0.01m, stop: 57000m), _none).ConfigureAwait(false);
Assert.IsNull(refusal);
await s.Rig.TurnsAsync(s.Manager, 6, _minute).ConfigureAwait(false);
var orders = await OrdersAsync(s.Rig).ConfigureAwait(false);
var entries = orders.Where(o => o.Purpose == "entry").ToList();
Assert.HasCount(4, entries);
// Three post-only steps at the best bid, each canceled after a minute, then an aggressive limit at mid + 0.5%.
Assert.IsTrue(entries.Take(3).All(o => o.Kind == "limit" && o.PostOnly && o.Limit == 60000m && o.Status == "canceled"));
Assert.AreEqual(("limit", false, OrderRules.RoundDown(60005m * 1.005m, 0.1m), "filled"), (entries[3].Kind, entries[3].PostOnly, entries[3].Limit, entries[3].Status));
Assert.AreEqual(4, entries.Select(o => o.ClientId).Distinct().Count(), "Every step is a new id.");
Assert.AreEqual("done/filled", await ExecutionStatusAsync(s.Rig, execution!.Value).ConfigureAwait(false));
var events = await s.Rig.QueryAsync("SELECT from_status, to_status FROM order_events e JOIN orders o ON o.id = e.order_id WHERE o.client_order_id = @c ORDER BY e.occurred_at, e.id",
r => (r.TextOrNull("from_status") ?? "") + ">" + r.Text("to_status"), ("c", entries[0].ClientId)).ConfigureAwait(false);
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, 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));
// One trigger order on OKX for the whole quantity, valid until canceled (SPEC 7.2).
var stop = orders.Single(o => o.Purpose == "stop");
Assert.AreEqual(("stop", "submitted", 0.00998m, 57000m, "gtc"), (stop.Kind, stop.Status, stop.Quantity, stop.Stop, stop.Tif));
Assert.AreEqual(OrderPurpose.Stop, ClientOrderIds.Parse(stop.ClientId)!.Purpose);
Assert.AreEqual(stop.ClientId, (await s.Paper.GetOpenOrdersAsync(_none).ConfigureAwait(false)).Single().ClientOrderId);
}
[TestMethod]
[TestCategory(Category.Simulation)]
public async Task ABuyIsGivenUpWhenEvenTheAggressiveLimitDoesNotFill()
{
await using var s = await OkxAsync(bid: 60000m, ask: 61000m).ConfigureAwait(false);
var (execution, _) = await s.Manager.SubmitAsync(Buy(s, 0.01m, stop: 57000m), _none).ConfigureAwait(false);
await s.Rig.TurnsAsync(s.Manager, 7, _minute).ConfigureAwait(false);
Assert.AreEqual("canceled/not_filled", await ExecutionStatusAsync(s.Rig, execution!.Value).ConfigureAwait(false));
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, StrategyNames.CryptoTrend, _none).ConfigureAwait(false));
Assert.IsEmpty(await s.Paper.GetOpenOrdersAsync(_none).ConfigureAwait(false), "Nothing left working.");
}
[TestMethod]
[TestCategory(Category.Simulation)]
public async Task ASaleIsNeverGivenUpAndAlertsAfterFiveMinutes()
{
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, 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;
var (execution, _) = await s.Manager.SubmitAsync(Sell(s, held), _none).ConfigureAwait(false);
await s.Rig.TurnsAsync(s.Manager, 3, _minute).ConfigureAwait(false);
Assert.AreEqual("working/", await ExecutionStatusAsync(s.Rig, execution!.Value).ConfigureAwait(false));
Assert.IsTrue((await OrdersAsync(s.Rig).ConfigureAwait(false)).Any(o => o.Purpose == "stop" && o.Status == "submitted"), "Without a price the stops stay.");
s.Rig.QuotesDown = false;
// Nobody buys near the price: the sale keeps going with a fresh reference and double tolerance.
s.Rig.Quote("BTC-EUR", 50000m, 60000m);
await s.Rig.TurnsAsync(s.Manager, 12, _minute).ConfigureAwait(false);
Assert.AreEqual("working/", await ExecutionStatusAsync(s.Rig, execution!.Value).ConfigureAwait(false));
var tolerance = (await s.Rig.QueryAsync("SELECT tolerance FROM executions WHERE id = @id", r => r.Money("tolerance"), ("id", execution)).ConfigureAwait(false)).Single();
Assert.AreEqual(0.01m, tolerance);
var alerts = await s.Rig.QueryAsync("SELECT kind FROM notifications WHERE kind = 'sell_not_filled'", r => r.Text("kind")).ConfigureAwait(false);
Assert.HasCount(1, alerts, "One alert, then it carries on.");
Assert.IsFalse((await OrdersAsync(s.Rig).ConfigureAwait(false)).Any(o => o.Purpose == "exit" && o.Kind == "market"), "Never a market order for a strategy's exit.");
Assert.IsFalse((await OrdersAsync(s.Rig).ConfigureAwait(false)).Any(o => o.Purpose == "stop" && o.Status == "submitted"), "The stops leave before the sale.");
// Buyers come back: sold, the trade closes.
s.Rig.Quote("BTC-EUR", 59990m, 60000m);
await s.Rig.TurnsAsync(s.Manager, 3, _minute).ConfigureAwait(false);
Assert.AreEqual("done/filled", await ExecutionStatusAsync(s.Rig, execution.Value).ConfigureAwait(false));
Assert.AreEqual("closed", (await s.Rig.QueryAsync("SELECT status FROM trades", r => r.Text("status")).ConfigureAwait(false)).Single());
}
[TestMethod]
[TestCategory(Category.Simulation)]
public async Task AtMostSixSendsAMinuteWithSalesAndStepsFirst()
{
await using var s = await OkxAsync().ConfigureAwait(false);
var coins = new List<Instrument>();
for (var i = 1; i <= 9; i++)
{
var coin = await s.Rig.InstrumentAsync(MarketDataStoreTests.Okx($"C{i}-EUR") with { TickSize = 0.01m, LotSize = 0.0001m, MinSize = 0.001m }).ConfigureAwait(false);
s.Rig.Quote(coin.Symbol, 100m, 100.10m);
coins.Add(coin);
}
TradeIntent BuyOf(Instrument coin, bool aggressive = false) =>
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, StrategyNames.CryptoTrend, _none).ConfigureAwait(false))!.Quantity;
var buys = new List<Guid>();
foreach (var coin in coins.Take(8))
{
buys.Add((await s.Manager.SubmitAsync(BuyOf(coin), _none).ConfigureAwait(false)).Execution!.Value);
}
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);
// Six sends: the sale first, then five new buys; three buys wait in line. Stops do not count.
var sent = await s.Rig.QueryAsync("SELECT execution_id FROM orders WHERE purpose IN ('entry', 'exit') AND created_at > @t", r => r.Id("execution_id"),
("t", TradingRig.Start.AddMinutes(3))).ConfigureAwait(false);
Assert.HasCount(6, sent);
Assert.Contains(sale, sent);
Assert.AreEqual(5, sent.Count(buys.Contains));
// Within the same minute nothing else goes.
await s.Rig.TurnsAsync(s.Manager, 1, TimeSpan.FromSeconds(31)).ConfigureAwait(false);
Assert.HasCount(6, await s.Rig.QueryAsync("SELECT id FROM orders WHERE purpose IN ('entry', 'exit') AND created_at > @t", r => r.Id("id"), ("t", TradingRig.Start.AddMinutes(3))).ConfigureAwait(false));
// The next minute: the sale and the five buys already working take their next step; the three new buys still wait.
await s.Rig.TurnsAsync(s.Manager, 1, TimeSpan.FromSeconds(30)).ConfigureAwait(false);
var started = await s.Rig.QueryAsync("SELECT DISTINCT execution_id FROM orders WHERE purpose = 'entry' AND created_at > @t", r => r.Id("execution_id"),
("t", TradingRig.Start.AddMinutes(3))).ConfigureAwait(false);
Assert.HasCount(5, started.Where(buys.Contains).ToList());
Assert.HasCount(12, await s.Rig.QueryAsync("SELECT id FROM orders WHERE purpose IN ('entry', 'exit') AND created_at > @t", r => r.Id("id"), ("t", TradingRig.Start.AddMinutes(3))).ConfigureAwait(false));
Assert.AreEqual(0, s.Manager.Pacer.Available);
}
[TestMethod]
[TestCategory(Category.Simulation)]
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: 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);
Assert.AreEqual((0.5m, "day"), (stops[0].Quantity, stops[0].Tif));
Assert.AreEqual((10m, "gtc"), (stops[1].Quantity, stops[1].Tif));
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: 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"));
var now = all.Where(o => o.Purpose == "stop" && o.Status == "submitted").OrderBy(o => o.Quantity).ToList();
Assert.AreEqual((0.5m, "day", 15m, "gtc"), (now[0].Quantity, now[0].Tif, now[1].Quantity, now[1].Tif));
Assert.IsGreaterThan(ClientOrderIds.Parse(stops[1].ClientId)!.Sequence, ClientOrderIds.Parse(now[0].ClientId)!.Sequence, "A new send, a new progressive.");
// At the close the day stop expires; the GTC one fires overnight: the two count as one, the rest is sold at once.
await s.Paper.ExpireDayOrdersAsync(_none).ConfigureAwait(false);
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, 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());
}
[TestMethod]
[TestCategory(Category.Simulation)]
public async Task AStopAlreadyPassedSellsAtMarketUnlessASplitExplainsIt()
{
await using (var s = await OkxAsync().ConfigureAwait(false))
{
await s.Manager.SubmitAsync(Buy(s, 0.01m, aggressive: true), _none).ConfigureAwait(false);
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, 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, 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));
}
// The morning of a 4-for-1 split the broker already shows a quarter of the price: a stop at the old level is
// not placed and nothing is sold; the split is applied and the stop follows it.
var applied = false;
await using var a = await AlpacaAsync((instrument, _) =>
{
var first = !applied;
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: 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, 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, 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");
Assert.AreEqual((40m, 95m), (stop.Quantity, stop.Stop));
Assert.AreEqual(40m, (await a.Paper.GetPositionsAsync(_none).ConfigureAwait(false)).Single().Quantity, "The simulator's book follows the same split.");
}
[TestMethod]
[TestCategory(Category.Simulation)]
public async Task ALostAnswerIsNeverSentTwiceDuplicateFillsCountOnceAndRefusalsEndTheBuy()
{
await using var s = await OkxAsync().ConfigureAwait(false);
var faulty = new FaultyBroker(s.Paper) { LoseNextAnswer = true, DuplicateFills = true };
var manager = s.Rig.Manager(faulty, s.Account);
var (execution, _) = await manager.SubmitAsync(Buy(s, 0.01m, stop: 57000m, aggressive: true), _none).ConfigureAwait(false);
await s.Rig.TurnsAsync(manager, 1, TimeSpan.FromSeconds(5)).ConfigureAwait(false);
var lost = (await OrdersAsync(s.Rig).ConfigureAwait(false)).Single();
Assert.AreEqual("created", lost.Status, "The answer was lost: the bot does not know yet.");
// Restart in the middle of the order: a new manager asks the broker before resending and finds it.
var restarted = s.Rig.Manager(faulty, s.Account);
await s.Rig.TurnsAsync(restarted, 3, TimeSpan.FromSeconds(5)).ConfigureAwait(false);
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, StrategyNames.CryptoTrend, _none).ConfigureAwait(false))!.Quantity);
// A refused buy ends, with its reason in the diary.
faulty.RejectNext = "insufficient";
var (refused, _) = await restarted.SubmitAsync(Buy(s, 0.01m, aggressive: true), _none).ConfigureAwait(false);
await s.Rig.TurnsAsync(restarted, 2, TimeSpan.FromSeconds(5)).ConfigureAwait(false);
Assert.AreEqual("canceled/rejected_insufficient", await ExecutionStatusAsync(s.Rig, refused!.Value).ConfigureAwait(false));
Assert.HasCount(1, await s.Rig.QueryAsync("SELECT id FROM journal WHERE code = 'order_rejected'", r => r.Id("id")).ConfigureAwait(false));
// A prudent account takes no new entries; exits still go (SPEC 7.4).
await s.Rig.Db.WriteAsync(x => x.ExecuteAsync("INSERT INTO account_status (id, account_id, mode, created_at, updated_at) VALUES (@id, @a, 'prudent', @now, @now)", _none,
("id", Ids.NewId(s.Rig.Clock)), ("a", s.Account.AccountId), ("now", s.Rig.Clock.UtcNow)), _none).ConfigureAwait(false);
Assert.AreEqual(OrderReasons.PrudentMode, (await restarted.SubmitAsync(Buy(s, 0.01m), _none).ConfigureAwait(false)).Refusal);
Assert.IsNull((await restarted.SubmitAsync(Sell(s, 0.005m), _none).ConfigureAwait(false)).Refusal);
}
[TestMethod]
[TestCategory(Category.Simulation)]
public async Task WhatCannotBeSoldAfterAnExitIsWrittenOffAndListedApart()
{
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, 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, 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());
Assert.IsEmpty(await s.Paper.GetOpenOrdersAsync(_none).ConfigureAwait(false), "No stop for a residue the bot no longer owns.");
Assert.AreEqual(80_000m, (await s.Paper.GetPositionsAsync(_none).ConfigureAwait(false)).Single().Quantity, "The residue stays on the account.");
}
}