Record the course the user chose on 2 December 2026 and make the container the only form of Anubis. - ADR 0021-0026: new roadmap (phases 10-24, readings per phase, the spec-to-ADR table, merge and tag only after the user's yes), Docker only, maths-only decisions, bans turned into limits on margin accounts, eToro Demo as currency venue and forward tests, strategy championship. ROADMAP rewritten from phase 10; STATE, CLAUDE.md, SVILUPPO, README, API-NOTES and the manuals without the desktop. - Remove the desktop: Anubis.Desktop, Anubis.Setup, deploy/windows, release-win and desktop-win, config.toml, PlatformKind, ANUBIS_PLATFORM, DPAPI with the ProtectedData package and the first-run wizard. Outside a container the server needs --data-dir, listens on 127.0.0.1 only and refuses foreign hosts; server and guard refuse --platform desktop with an Italian message and exit code 2. The demo keeps its key in a file and its error-page choices need no startup password. The diagnostics report says where the server runs from its own environment. - Lighter image: restore and publish for linux-x64 only, and leave out the Windows libraries ONNX Runtime copies anyway (829 MB to 410 MB on disk, /app from 282 MB to 42 MB). Rotating Docker logs in the Unraid template, the manual and the compose; backtest and learning run as one-shot commands. tasks dev uses artifacts/dev-data. refs #113 #114 #115 #78 #80 #81 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
179 lines
11 KiB
C#
179 lines
11 KiB
C#
using Anubis.Brokers;
|
|
using Anubis.Core;
|
|
using Anubis.Data;
|
|
using Anubis.Platform;
|
|
using Anubis.Trading;
|
|
|
|
namespace Anubis.Tests;
|
|
|
|
/// <summary>Rules without a database: order ids, rounding, the state machine, returns, the live guard (issues #26, #27, #29).</summary>
|
|
[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<ArgumentOutOfRangeException>(() =>
|
|
ClientOrderIds.Build(installation, TradingEnvironments.Demo, StrategyNames.CryptoTrend, OrderPurpose.Entry, key, ClientOrderIds.MaxSequence + 1));
|
|
Assert.ThrowsExactly<ArgumentException>(() => 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<BrokerException>(() => 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<OrderStatus>())
|
|
{
|
|
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<LiveTradingRefusedException>(() => LiveGuard.Ensure(TradingEnvironments.Live, TradingConsent.None));
|
|
Assert.ThrowsExactly<ArgumentException>(() => 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<string, string?> { ["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<LiveTradingRefusedException>(() => LiveGuard.Ensure(TradingEnvironments.Live, docker));
|
|
env["ANUBIS_ALLOW_LIVE"] = "0";
|
|
Assert.ThrowsExactly<LiveTradingRefusedException>(() => LiveGuard.Ensure(TradingEnvironments.Live, TradingConsent.From(DockerPlatform.Load(env))));
|
|
|
|
var refused = Assert.ThrowsExactly<LiveTradingRefusedException>(() => LiveGuard.Ensure(TradingEnvironments.Live, docker));
|
|
Assert.Contains("ANUBIS_ALLOW_LIVE", refused.Message, "The only switch for real money is the variable of the container (ADR 0022).");
|
|
}
|
|
|
|
[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<LiveTradingRefusedException>(() =>
|
|
new AlpacaTrading(client, clock, new AlpacaCredentials("fake-key-id", "fake-secret"), new AlpacaTradingOptions { Environment = TradingEnvironments.Live }, TradingConsent.None));
|
|
Assert.ThrowsExactly<LiveTradingRefusedException>(() =>
|
|
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.");
|
|
}
|
|
}
|