using Anubis.Brokers;
using Anubis.Core;
using Anubis.Data;
using Anubis.Platform;
using Anubis.Trading;
namespace Anubis.Tests;
/// Rules without a database: order ids, rounding, the state machine, returns, the live guard (issues #26, #27, #29).
[TestClass]
public sealed class TradingRulesTests
{
internal static InstrumentSpec Stock(string symbol, bool fractionable = true) =>
new(Venues.Alpaca, symbol, symbol, AssetClasses.Equity, "USD") { Fractionable = fractionable, TickSize = 0.01m, Status = "active", Exchange = "NASDAQ" };
[TestMethod]
[TestCategory(Category.Unit)]
public void ClientOrderIdsAreShortDeterministicAndReadable()
{
var installation = ClientOrderIds.InstallationCode(Guid.Parse("0193a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b"));
var key = ClientOrderIds.Key(Guid.Parse("0193a1b2-0000-7000-8000-000000000001"));
Assert.AreEqual(installation, ClientOrderIds.InstallationCode(Guid.Parse("0193a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b")));
Assert.AreEqual(key, ClientOrderIds.Key(Guid.Parse("0193a1b2-0000-7000-8000-000000000001")));
var id = ClientOrderIds.Build(installation, TradingEnvironments.Demo, StrategyNames.EquityMomentum, OrderPurpose.Stop, key, 1297);
Assert.AreEqual(ClientOrderIds.Length, id.Length);
Assert.IsLessThanOrEqualTo(32, id.Length);
Assert.IsTrue(id.StartsWith("ANU", StringComparison.Ordinal));
Assert.IsTrue(id.All(char.IsAsciiLetterOrDigit), id);
// From the id alone: strategy, environment, purpose and progressive (SPEC 7.2, 15.1).
var parts = ClientOrderIds.Parse(id);
Assert.IsNotNull(parts);
Assert.AreEqual(new ClientOrderIdParts(installation, TradingEnvironments.Demo, StrategyNames.EquityMomentum, OrderPurpose.Stop, key, 1297), parts);
Assert.IsTrue(ClientOrderIds.IsOurs(id, installation));
Assert.IsFalse(ClientOrderIds.IsOurs(id, "ZZZZ"), "Another installation's order is not ours.");
Assert.IsFalse(ClientOrderIds.IsOurs("my-own-order-123", installation), "The user's own orders are never touched.");
Assert.IsNull(ClientOrderIds.Parse(null));
// Every progressive gives a different id; the next one is a different order.
Assert.AreNotEqual(id, ClientOrderIds.Build(installation, TradingEnvironments.Demo, StrategyNames.EquityMomentum, OrderPurpose.Stop, key, 1298));
Assert.ThrowsExactly(() =>
ClientOrderIds.Build(installation, TradingEnvironments.Demo, StrategyNames.CryptoTrend, OrderPurpose.Entry, key, ClientOrderIds.MaxSequence + 1));
Assert.ThrowsExactly(() => ClientOrderIds.Build(installation, TradingEnvironments.Demo, "unknown", OrderPurpose.Entry, key, 1));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void OrdersAreRoundedToTickAndLotAndCheckedAgainstMinimums()
{
var btc = MarketDataStoreTests.Okx("BTC-EUR") with { MinSize = 0.00001m, TickSize = 0.1m };
// Quantity down to the lot; a buy limit rounds down and a sell limit up, never past the price asked.
var buy = OrderRules.Round(btc, OrderSide.Buy, OrderKind.Limit, 0.0123456789m, 60000m, 60000.17m);
Assert.AreEqual(new RoundedOrder(0.01234567m, 60000.1m, null, null), buy);
Assert.AreEqual(60000.2m, OrderRules.Round(btc, OrderSide.Sell, OrderKind.Limit, 0.01m, 60000m, 60000.17m).LimitPrice);
Assert.AreEqual(OrderReasons.BelowMinimumSize, OrderRules.Round(btc, OrderSide.Buy, OrderKind.Limit, 0.000009m, 60000m, 60000m).Rejection);
Assert.AreEqual(OrderReasons.ZeroQuantity, OrderRules.Round(btc, OrderSide.Buy, OrderKind.Limit, 0m, 60000m).Rejection);
Assert.AreEqual(OrderReasons.InstrumentClosed, OrderRules.Round(btc with { Status = "suspend" }, OrderSide.Buy, OrderKind.Limit, 1m, 60000m).Rejection);
// Alpaca: whole shares when not fractionable, nine decimals otherwise, never below 1 $ of value.
Assert.AreEqual(3m, OrderRules.Round(Stock("XYZ", fractionable: false), OrderSide.Buy, OrderKind.Limit, 3.9m, 50m, 50m).Quantity);
Assert.AreEqual(0.123456789m, OrderRules.Round(Stock("MSFT"), OrderSide.Buy, OrderKind.Limit, 0.1234567891m, 400m, 400m).Quantity);
Assert.AreEqual(OrderReasons.BelowMinimumNotional, OrderRules.Round(Stock("MSFT"), OrderSide.Buy, OrderKind.Limit, 0.002m, 400m, 400m).Rejection);
// A stop protects even a quantity below the minimum value; a stop level rounds up, so it fires a little earlier.
var stop = OrderRules.Round(Stock("MSFT"), OrderSide.Sell, OrderKind.Stop, 0.002m, 400m, stopPrice: 380.123m);
Assert.IsTrue(stop.IsValid);
Assert.AreEqual(380.13m, stop.StopPrice);
// The Alpaca catalogue has no tick: 2 decimals from 1 $, 4 below, as Alpaca asks (else 422 sub-penny).
var asListed = Stock("MSFT") with { TickSize = null };
Assert.AreEqual(380.13m, OrderRules.Round(asListed, OrderSide.Sell, OrderKind.Stop, 1m, 400m, stopPrice: 380.123m).StopPrice);
Assert.AreEqual(0.4568m, OrderRules.Round(asListed, OrderSide.Sell, OrderKind.Stop, 10m, 0.5m, stopPrice: 0.45671m).StopPrice);
Assert.AreEqual(412.34m, OrderRules.Round(asListed, OrderSide.Buy, OrderKind.Limit, 1m, 412m, 412.345m).LimitPrice);
Assert.AreEqual((12m, 0.345m), OrderRules.SplitWhole(12.345m));
Assert.IsTrue(OrderRules.IsUnsellable(btc, 0.000005m, 60000m));
Assert.IsFalse(OrderRules.IsUnsellable(btc, 0.001m, 60000m));
}
[TestMethod]
[TestCategory(Category.Unit)]
public async Task OkxCountsAnOrderAsUnknownOnlyWhenItDoesNotExist()
{
var answer = "{\"code\":\"51603\",\"msg\":\"Order does not exist\",\"data\":[]}";
var http = new FakeHttp()
.On("/api/v5/public/time", "{\"code\":\"0\",\"msg\":\"\",\"data\":[{\"ts\":\"1597026383085\"}]}")
.On(u => u.AbsolutePath == "/api/v5/trade/order", _ => FakeHttp.Respond(answer));
using var client = http.Client();
var okx = new OkxTrading(client, new ManualClock(TradingRig.Start), new OkxCredentials("fake-key", "fake-secret", "fake-pass"),
new OkxTradingOptions { Environment = TradingEnvironments.Demo }, TradingConsent.None);
Assert.IsNull(await okx.GetOrderAsync("ANUX1", "BTC-EUR", CancellationToken.None));
// A generic failure is not "unknown": taken as such, a lost order could be sent twice.
answer = "{\"code\":\"1\",\"msg\":\"Operation failed.\",\"data\":[]}";
await Assert.ThrowsAsync(() => okx.GetOrderAsync("ANUX1", "BTC-EUR", CancellationToken.None));
}
[TestMethod]
[TestCategory(Category.Unit)]
public void ARefusedSaleIsTriedAgainWithGrowingPauses() =>
CollectionAssert.AreEqual(new[] { 1, 2, 4, 8, 15, 15 }, Enumerable.Range(1, 6).Select(n => (int)OrderManager.RefusalPause(n).TotalMinutes).ToArray());
[TestMethod]
[TestCategory(Category.Unit)]
public void OrderStatesOnlyMoveForward()
{
Assert.IsTrue(OrderStates.CanMove(OrderStatus.Created, OrderStatus.Submitted));
Assert.IsTrue(OrderStates.CanMove(OrderStatus.Submitted, OrderStatus.PartiallyFilled));
Assert.IsTrue(OrderStates.CanMove(OrderStatus.PartiallyFilled, OrderStatus.PartiallyFilled), "More of the order filled.");
Assert.IsTrue(OrderStates.CanMove(OrderStatus.PartiallyFilled, OrderStatus.Filled));
Assert.IsTrue(OrderStates.CanMove(OrderStatus.Created, OrderStatus.Filled), "A fill that arrives before the acknowledgement.");
Assert.IsFalse(OrderStates.CanMove(OrderStatus.PartiallyFilled, OrderStatus.Submitted));
Assert.IsFalse(OrderStates.CanMove(OrderStatus.Submitted, OrderStatus.Created));
foreach (var final in new[] { OrderStatus.Filled, OrderStatus.Canceled, OrderStatus.Rejected, OrderStatus.Expired })
{
Assert.IsTrue(OrderStates.IsFinal(final));
foreach (var to in Enum.GetValues())
{
Assert.IsFalse(OrderStates.CanMove(final, to), $"{final} → {to}");
}
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void TimeWeightedReturnIgnoresDepositsAndWithdrawals()
{
// 1000 → 1100 (+10%), then 1000 more is given: 2100 → 2310 (+10%). The return is 21%, not 131%.
(decimal, decimal)[] points = [(0m, 0m), (1000m, 1000m), (1100m, 1000m), (2100m, 2000m), (2310m, 2000m)];
Assert.AreEqual(0.21m, Math.Round(Returns.TimeWeighted(points), 10));
// A withdrawal is not a loss.
(decimal, decimal)[] withdrawal = [(1000m, 1000m), (1000m, 1000m), (500m, 500m)];
Assert.AreEqual(0m, Returns.TimeWeighted(withdrawal));
// 1000 $ given at 1.10 $/€ and still 1000 $: at 1.25 $/€ the euro value fell by the exchange rate alone.
var effect = Returns.FxEffect([(1000m, 1.10m)], 1.25m);
Assert.AreEqual(Math.Round(1000m / 1.25m - 1000m / 1.10m, 10), Math.Round(effect, 10));
Assert.IsLessThan(0m, effect);
}
[TestMethod]
[TestCategory(Category.Unit)]
public void RealAccountsAreRefusedWithoutTheStartupConsent()
{
Assert.ThrowsExactly(() => LiveGuard.Ensure(TradingEnvironments.Live, TradingConsent.None));
Assert.ThrowsExactly(() => LiveGuard.Ensure("production", TradingConsent.None));
LiveGuard.Ensure(TradingEnvironments.Demo, TradingConsent.None);
LiveGuard.Ensure(TradingEnvironments.Simulation, TradingConsent.None);
// Docker without the variable, or with 0: refused.
var env = new Dictionary { ["ANUBIS_DB_ENGINE"] = "sqlite", ["ANUBIS_SECRET_KEY"] = new string('k', 40), ["ANUBIS_ADMIN_PASSWORD"] = "initial-pass-1" };
var docker = TradingConsent.From(DockerPlatform.Load(env));
Assert.IsFalse(docker.AllowLive);
Assert.ThrowsExactly(() => LiveGuard.Ensure(TradingEnvironments.Live, docker));
env["ANUBIS_ALLOW_LIVE"] = "0";
Assert.ThrowsExactly(() => LiveGuard.Ensure(TradingEnvironments.Live, TradingConsent.From(DockerPlatform.Load(env))));
// Desktop: the config.toml the wizard writes keeps real money off.
var root = TempFolder.Create("live");
try
{
var data = new DataDirectory(root);
var store = new RestrictedFileStore(Path.Combine(root, "keys"));
DesktopPlatform.WriteConfig(data, store, new DbSettings { Engine = DbEngine.Sqlite });
var desktop = TradingConsent.From(DesktopPlatform.Load(data, store));
Assert.IsFalse(desktop.AllowLive);
var refused = Assert.ThrowsExactly(() => LiveGuard.Ensure(TradingEnvironments.Live, desktop));
Assert.Contains("config.toml", refused.Message);
}
finally
{
TempFolder.Delete(root);
}
}
[TestMethod]
[TestCategory(Category.Unit)]
public void BrokerAdaptersRefuseARealAccountBeforeAnyRequest()
{
var http = new FakeHttp();
using var client = new HttpClient(http);
var clock = new ManualClock(new DateTimeOffset(2026, 11, 10, 15, 0, 0, TimeSpan.Zero));
Assert.ThrowsExactly(() =>
new AlpacaTrading(client, clock, new AlpacaCredentials("fake-key-id", "fake-secret"), new AlpacaTradingOptions { Environment = TradingEnvironments.Live }, TradingConsent.None));
Assert.ThrowsExactly(() =>
new OkxTrading(client, clock, new OkxCredentials("fake-key", "fake-secret", "fake-pass"), new OkxTradingOptions { Environment = TradingEnvironments.Live }, TradingConsent.None));
Assert.AreEqual(0, http.Requests.Count, "Nothing may leave before the guard.");
}
}