using Anubis.Data; using Anubis.Trading; namespace Anubis.Tests; /// The internal simulator (issue #26, SPEC 7.3): realistic and prudent fills. [TestClass] public sealed class PaperBrokerTests { private static readonly CancellationToken _none = CancellationToken.None; private static OrderRequest Limit(string id, string symbol, OrderSide side, decimal quantity, decimal price, bool postOnly = false, TimeInForce tif = TimeInForce.Gtc) => new(id, symbol, side, OrderKind.Limit, quantity, tif) { LimitPrice = price, PostOnly = postOnly }; [TestMethod] [TestCategory(Category.Simulation)] public async Task LimitsFillOnlyWhenCrossedAndTakersPaySlippageAndTheListFee() { await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); var paper = rig.Paper(PaperOptions.Okx(), account.AccountId); await paper.DepositAsync(10000m, "EUR", _none).ConfigureAwait(false); rig.Quote("BTC-EUR", 60000m, 60010m); // A buy below the market rests; touching the limit is not enough, the market must go through it. await paper.SubmitOrderAsync(Limit("B1", "BTC-EUR", OrderSide.Buy, 0.01m, 59990m), _none).ConfigureAwait(false); await paper.PumpAsync(_none).ConfigureAwait(false); rig.Quote("BTC-EUR", 59980m, 59990m); Assert.AreEqual(OrderStatus.Submitted, (await paper.GetOrderAsync("B1", "BTC-EUR", _none).ConfigureAwait(false))!.Status, "Touched, not crossed."); rig.Quote("BTC-EUR", 59970m, 59985m); var filled = (await paper.GetOrderAsync("B1", "BTC-EUR", _none).ConfigureAwait(false))!; Assert.AreEqual(OrderStatus.Filled, filled.Status); // Maker on OKX: 0.10% kept in the coin (SPEC 4.2), filled at the order's own price. var fill = (await paper.GetFillsAsync(TradingRig.Start, _none).ConfigureAwait(false)).Single(); Assert.AreEqual((59990m, 0.00001m, "BTC"), (fill.Price, fill.Fee, fill.FeeCurrency)); Assert.AreEqual(0.00999m, (await paper.GetPositionsAsync(_none).ConfigureAwait(false)).Single().Quantity); // A market sale takes the bid less 5 basis points and pays the taker fee, 0.20%, in euro. await paper.SubmitOrderAsync(new OrderRequest("S1", "BTC-EUR", OrderSide.Sell, OrderKind.Market, 0.00999m, TimeInForce.Ioc), _none).ConfigureAwait(false); await paper.PumpAsync(_none).ConfigureAwait(false); var sale = (await paper.GetFillsAsync(TradingRig.Start, _none).ConfigureAwait(false)).Single(f => f.ClientOrderId == "S1"); Assert.AreEqual(OrderRules.RoundDown(59970m * 0.9995m, 0.1m), sale.Price); Assert.AreEqual(Math.Round(0.00999m * sale.Price * 0.002m, 18), sale.Fee); Assert.AreEqual("EUR", sale.FeeCurrency); // A post-only order that would take liquidity is canceled, as on OKX. await paper.SubmitOrderAsync(Limit("B2", "BTC-EUR", OrderSide.Buy, 0.01m, 60000m, postOnly: true), _none).ConfigureAwait(false); var postOnly = (await paper.GetOrderAsync("B2", "BTC-EUR", _none).ConfigureAwait(false))!; Assert.AreEqual((OrderStatus.Canceled, "post_only_would_take"), (postOnly.Status, postOnly.Reason)); // Partial fills follow the size on offer. rig.Quote("BTC-EUR", 59970m, 59985m, size: 0.004m); await paper.SubmitOrderAsync(Limit("B3", "BTC-EUR", OrderSide.Buy, 0.01m, 60000m), _none).ConfigureAwait(false); var partial = (await paper.GetOrderAsync("B3", "BTC-EUR", _none).ConfigureAwait(false))!; Assert.AreEqual((OrderStatus.PartiallyFilled, 0.004m), (partial.Status, partial.FilledQuantity)); } [TestMethod] [TestCategory(Category.Simulation)] public async Task OrdersWaitForTheSimulatedLatencyAndTheBookSurvivesARestart() { await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); using var paper = new PaperBroker(PaperOptions.Okx(), rig.Clock, rig.QuoteAsync, rig.Spec, new PaperBookStore(rig.Db, rig.Clock, account.AccountId)); await paper.DepositAsync(10000m, "EUR", _none).ConfigureAwait(false); rig.Quote("BTC-EUR", 60000m, 60010m); await paper.SubmitOrderAsync(new OrderRequest("M1", "BTC-EUR", OrderSide.Buy, OrderKind.Market, 0.01m, TimeInForce.Ioc), _none).ConfigureAwait(false); await paper.PumpAsync(_none).ConfigureAwait(false); Assert.AreEqual(OrderStatus.Submitted, (await paper.GetOrderAsync("M1", "BTC-EUR", _none).ConfigureAwait(false))!.Status, "Not before 300 ms."); rig.Clock.Advance(TimeSpan.FromSeconds(1)); rig.Quote("BTC-EUR", 60000m, 60010m); Assert.AreEqual(OrderStatus.Filled, (await paper.GetOrderAsync("M1", "BTC-EUR", _none).ConfigureAwait(false))!.Status, "Within 1,000 ms."); // Another instance on the same account reads the same book. using var again = new PaperBroker(PaperOptions.Okx(), rig.Clock, rig.QuoteAsync, rig.Spec, new PaperBookStore(rig.Db, rig.Clock, account.AccountId)); Assert.AreEqual(OrderStatus.Filled, (await again.GetOrderAsync("M1", "BTC-EUR", _none).ConfigureAwait(false))!.Status); Assert.HasCount(1, await again.GetPositionsAsync(_none).ConfigureAwait(false)); // Sending the same id twice gives back the same order (idempotency). var first = await again.SubmitOrderAsync(Limit("L1", "BTC-EUR", OrderSide.Buy, 0.001m, 50000m), _none).ConfigureAwait(false); var second = await again.SubmitOrderAsync(Limit("L1", "BTC-EUR", OrderSide.Buy, 0.001m, 50000m), _none).ConfigureAwait(false); Assert.AreEqual(first.BrokerOrderId, second.BrokerOrderId); Assert.HasCount(1, await again.GetOpenOrdersAsync(_none).ConfigureAwait(false)); } [TestMethod] [TestCategory(Category.Simulation)] public async Task AlpacaRulesAndFeesAreTheBrokersOwn() { await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); var account = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Simulation).ConfigureAwait(false); await rig.InstrumentAsync(TradingRig.Stock("MSFT")).ConfigureAwait(false); var paper = rig.Paper(PaperOptions.Alpaca(), account.AccountId); await paper.DepositAsync(10000m, "USD", _none).ConfigureAwait(false); rig.Quote("MSFT", 400m, 400.10m); // Fractions only as day orders; an opposite order on the same symbol is refused (wash trade). var gtc = await Assert.ThrowsExactlyAsync(() => paper.SubmitOrderAsync(Limit("F1", "MSFT", OrderSide.Buy, 1.5m, 401m), _none)).ConfigureAwait(false); Assert.AreEqual("fractional_orders_must_be_day", gtc.Code); await paper.SubmitOrderAsync(Limit("B1", "MSFT", OrderSide.Buy, 10.5m, 401m, tif: TimeInForce.Day), _none).ConfigureAwait(false); await paper.PumpAsync(_none).ConfigureAwait(false); Assert.AreEqual(10.5m, (await paper.GetPositionsAsync(_none).ConfigureAwait(false)).Single().Quantity, "No fee in kind on stocks."); await paper.SubmitOrderAsync(new OrderRequest("S1", "MSFT", OrderSide.Sell, OrderKind.Stop, 10m, TimeInForce.Gtc) { StopPrice = 380m }, _none).ConfigureAwait(false); var wash = await Assert.ThrowsExactlyAsync(() => paper.SubmitOrderAsync(Limit("B2", "MSFT", OrderSide.Buy, 1m, 401m, tif: TimeInForce.Day), _none)).ConfigureAwait(false); Assert.AreEqual("opposite_side_order_open", wash.Code); // The stop reserves its shares: only the fraction can still be sold. var reserved = await Assert.ThrowsExactlyAsync(() => paper.SubmitOrderAsync(Limit("X1", "MSFT", OrderSide.Sell, 1m, 399m, tif: TimeInForce.Day), _none)).ConfigureAwait(false); Assert.AreEqual("insufficient_quantity", reserved.Code); // A sale pays the SEC fee on its value and the CAT fee per share, each rounded up to the cent. await paper.CancelOrderAsync("S1", "MSFT", _none).ConfigureAwait(false); await paper.SubmitOrderAsync(Limit("X2", "MSFT", OrderSide.Sell, 10m, 399m, tif: TimeInForce.Day), _none).ConfigureAwait(false); await paper.PumpAsync(_none).ConfigureAwait(false); var sale = (await paper.GetFillsAsync(TradingRig.Start, _none).ConfigureAwait(false)).Single(f => f.ClientOrderId == "X2"); var expected = OrderRules.RoundUp(10m * sale.Price * 0.0000206m, 0.01m) + OrderRules.RoundUp(10m * 0.000003m, 0.01m); Assert.AreEqual(expected, sale.Fee); } [TestMethod] [TestCategory(Category.Simulation)] public async Task AfterAnAbsenceStopsFireOnTheMinuteBarsAndBuysAreCanceled() { await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); var paper = rig.Paper(PaperOptions.Okx(), account.AccountId); await paper.DepositAsync(10000m, "EUR", _none).ConfigureAwait(false); rig.Quote("BTC-EUR", 60000m, 60010m); await paper.SubmitOrderAsync(new OrderRequest("M1", "BTC-EUR", OrderSide.Buy, OrderKind.Market, 0.01m, TimeInForce.Ioc), _none).ConfigureAwait(false); await paper.PumpAsync(_none).ConfigureAwait(false); await paper.SubmitOrderAsync(new OrderRequest("S1", "BTC-EUR", OrderSide.Sell, OrderKind.Stop, 0.00998m, TimeInForce.Gtc) { StopPrice = 57000m }, _none).ConfigureAwait(false); await paper.SubmitOrderAsync(Limit("B1", "BTC-EUR", OrderSide.Buy, 0.01m, 55000m), _none).ConfigureAwait(false); await paper.PumpAsync(_none).ConfigureAwait(false); // The bot is off for two hours; meanwhile a bar opens at 56,500, below the stop: the stop fills at the open. var off = rig.Clock.UtcNow; rig.Clock.Advance(TimeSpan.FromHours(2)); IReadOnlyList bars = [ new(off.AddMinutes(10), 58000, 58100, 57500, 57600, 1), new(off.AddMinutes(11), 56500, 56800, 56000, 56200, 1), ]; var handled = await paper.CatchUpAsync((_, _, _, _) => Task.FromResult(bars), _none).ConfigureAwait(false); Assert.AreEqual(2, handled); var stop = (await paper.GetFillsAsync(TradingRig.Start, _none).ConfigureAwait(false)).Single(f => f.ClientOrderId == "S1"); Assert.AreEqual(OrderRules.RoundDown(56500m * 0.9995m, 0.1m), stop.Price); Assert.AreEqual(off.AddMinutes(11).AddSeconds(30), stop.ExecutedAt); var buy = (await paper.GetOrderAsync("B1", "BTC-EUR", _none).ConfigureAwait(false))!; Assert.AreEqual((OrderStatus.Canceled, "canceled_after_absence"), (buy.Status, buy.Reason)); } }