From 1419457fe41436c4cc6b981a357fa3f89e25615e Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 10 Nov 2026 20:29:02 +0100 Subject: [PATCH 1/7] Add the trading core: ledger, simulator, order manager, reconciliation (refs #26 #27 #28 #29 #30) Phase 3 needs books the bot can trust before any strategy trades. This adds: - schema 0003: executions, order events, trades, residues, account status, reconciliations, capital changes, applied corporate actions, simulator books; - the broker interface with the internal simulator and the Alpaca paper and OKX demo adapters, all behind the live guard (SPEC 2.2); - the append-only ledger with lots, trades from zero to zero, residues, dividends, splits and reversals; capital entrusted per broker and equity photographs with time-weighted return and FX effect; - the order manager (chasing limit, pacing, sells never abandoned, server stops, breached-stop rule) and the reconciler with prudent mode; - the trading service wired into the host, off in demo mode and in tests. Ids made with one clock in the same millisecond now carry a counter (RFC 9562 method 1): two lots of one order kept a random order, which broke LIFO. Co-Authored-By: Claude Opus 5.5 --- src/Anubis.Server/AnubisHost.cs | 44 +- src/Anubis.Server/ServerOptions.cs | 3 + src/Anubis/Core/Format.cs | 16 + src/Anubis/Core/Ids.cs | 52 +- src/Anubis/Db/Migrations/0003_trading.sql | 195 +++++ src/Anubis/Trading/AlpacaTrading.cs | 451 ++++++++++ src/Anubis/Trading/Capital.cs | 175 ++++ src/Anubis/Trading/Diary.cs | 37 + src/Anubis/Trading/Equity.cs | 151 ++++ src/Anubis/Trading/Ledger.cs | 558 ++++++++++++ src/Anubis/Trading/LiveGuard.cs | 71 ++ src/Anubis/Trading/OkxTrading.cs | 459 ++++++++++ src/Anubis/Trading/OrderManager.Protection.cs | 325 +++++++ src/Anubis/Trading/OrderManager.cs | 756 ++++++++++++++++ src/Anubis/Trading/OrderRules.cs | 290 ++++++ src/Anubis/Trading/Orders.cs | 326 +++++++ src/Anubis/Trading/PaperBroker.cs | 825 ++++++++++++++++++ src/Anubis/Trading/Reconciler.cs | 536 ++++++++++++ src/Anubis/Trading/TradingHttp.cs | 92 ++ src/Anubis/Trading/TradingService.cs | 585 +++++++++++++ tests/Anubis.Tests/CoreTests.cs | 9 + .../Fixtures/alpaca-trading/account.json | 39 + .../Fixtures/alpaca-trading/activity-div.json | 10 + .../alpaca-trading/activity-fill.json | 13 + .../alpaca-trading/error-subpenny.json | 4 + .../Fixtures/alpaca-trading/order-crypto.json | 36 + .../Fixtures/alpaca-trading/order-limit.json | 36 + .../Fixtures/alpaca-trading/position.json | 20 + .../alpaca-trading/ws-authorized.json | 7 + .../Fixtures/alpaca-trading/ws-fill.json | 46 + .../Fixtures/alpaca-trading/ws-listening.json | 6 + .../Fixtures/okx-trading/account-config.json | 37 + .../Fixtures/okx-trading/algo-canceled.json | 14 + .../Fixtures/okx-trading/algo-placed.json | 14 + .../Fixtures/okx-trading/algos-pending.json | 65 ++ .../Fixtures/okx-trading/balance.json | 79 ++ .../Fixtures/okx-trading/fills.json | 34 + .../Fixtures/okx-trading/order-canceled.json | 15 + .../Fixtures/okx-trading/order-failed.json | 18 + .../Fixtures/okx-trading/order-filled.json | 62 ++ .../Fixtures/okx-trading/order-placed.json | 17 + .../Fixtures/okx-trading/orders-pending.json | 62 ++ .../Fixtures/okx-trading/trade-fee.json | 31 + .../Fixtures/okx-trading/ws-algo-live.json | 56 ++ .../Fixtures/okx-trading/ws-login.json | 6 + .../Fixtures/okx-trading/ws-order-filled.json | 84 ++ .../Fixtures/okx-trading/ws-subscribed.json | 10 + tests/Anubis.Tests/LedgerTests.cs | 262 ++++++ tests/Anubis.Tests/TradingRulesTests.cs | 163 ++++ tests/Anubis.Tests/TradingSupport.cs | 130 +++ 50 files changed, 7327 insertions(+), 5 deletions(-) create mode 100644 src/Anubis/Db/Migrations/0003_trading.sql create mode 100644 src/Anubis/Trading/AlpacaTrading.cs create mode 100644 src/Anubis/Trading/Capital.cs create mode 100644 src/Anubis/Trading/Diary.cs create mode 100644 src/Anubis/Trading/Equity.cs create mode 100644 src/Anubis/Trading/Ledger.cs create mode 100644 src/Anubis/Trading/LiveGuard.cs create mode 100644 src/Anubis/Trading/OkxTrading.cs create mode 100644 src/Anubis/Trading/OrderManager.Protection.cs create mode 100644 src/Anubis/Trading/OrderManager.cs create mode 100644 src/Anubis/Trading/OrderRules.cs create mode 100644 src/Anubis/Trading/Orders.cs create mode 100644 src/Anubis/Trading/PaperBroker.cs create mode 100644 src/Anubis/Trading/Reconciler.cs create mode 100644 src/Anubis/Trading/TradingHttp.cs create mode 100644 src/Anubis/Trading/TradingService.cs create mode 100644 tests/Anubis.Tests/Fixtures/alpaca-trading/account.json create mode 100644 tests/Anubis.Tests/Fixtures/alpaca-trading/activity-div.json create mode 100644 tests/Anubis.Tests/Fixtures/alpaca-trading/activity-fill.json create mode 100644 tests/Anubis.Tests/Fixtures/alpaca-trading/error-subpenny.json create mode 100644 tests/Anubis.Tests/Fixtures/alpaca-trading/order-crypto.json create mode 100644 tests/Anubis.Tests/Fixtures/alpaca-trading/order-limit.json create mode 100644 tests/Anubis.Tests/Fixtures/alpaca-trading/position.json create mode 100644 tests/Anubis.Tests/Fixtures/alpaca-trading/ws-authorized.json create mode 100644 tests/Anubis.Tests/Fixtures/alpaca-trading/ws-fill.json create mode 100644 tests/Anubis.Tests/Fixtures/alpaca-trading/ws-listening.json create mode 100644 tests/Anubis.Tests/Fixtures/okx-trading/account-config.json create mode 100644 tests/Anubis.Tests/Fixtures/okx-trading/algo-canceled.json create mode 100644 tests/Anubis.Tests/Fixtures/okx-trading/algo-placed.json create mode 100644 tests/Anubis.Tests/Fixtures/okx-trading/algos-pending.json create mode 100644 tests/Anubis.Tests/Fixtures/okx-trading/balance.json create mode 100644 tests/Anubis.Tests/Fixtures/okx-trading/fills.json create mode 100644 tests/Anubis.Tests/Fixtures/okx-trading/order-canceled.json create mode 100644 tests/Anubis.Tests/Fixtures/okx-trading/order-failed.json create mode 100644 tests/Anubis.Tests/Fixtures/okx-trading/order-filled.json create mode 100644 tests/Anubis.Tests/Fixtures/okx-trading/order-placed.json create mode 100644 tests/Anubis.Tests/Fixtures/okx-trading/orders-pending.json create mode 100644 tests/Anubis.Tests/Fixtures/okx-trading/trade-fee.json create mode 100644 tests/Anubis.Tests/Fixtures/okx-trading/ws-algo-live.json create mode 100644 tests/Anubis.Tests/Fixtures/okx-trading/ws-login.json create mode 100644 tests/Anubis.Tests/Fixtures/okx-trading/ws-order-filled.json create mode 100644 tests/Anubis.Tests/Fixtures/okx-trading/ws-subscribed.json create mode 100644 tests/Anubis.Tests/LedgerTests.cs create mode 100644 tests/Anubis.Tests/TradingRulesTests.cs create mode 100644 tests/Anubis.Tests/TradingSupport.cs diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs index 5816877..24f41f7 100644 --- a/src/Anubis.Server/AnubisHost.cs +++ b/src/Anubis.Server/AnubisHost.cs @@ -4,6 +4,7 @@ using Anubis.Data; using Anubis.Db; using Anubis.Demo; using Anubis.Platform; +using Anubis.Trading; namespace Anubis.Server; @@ -36,7 +37,7 @@ internal sealed record HostChanged(HostMode Mode); /// Everything that needs the database, built once it is reachable and the installation checks out. internal sealed record AppServices(Database Db, SettingsStore Settings, SecretStore Secrets, AccessStore Access, Backups Backups, Scheduler Scheduler, - MarketDataService? MarketData = null); + MarketDataService? MarketData = null, TradingService? Trading = null); /// /// The startup state machine of the server (SPEC 15.1, 15.6): reads the startup configuration, opens the configured @@ -63,6 +64,7 @@ internal sealed partial class AnubisHost( private Task? _schedulerLoop; private CancellationTokenSource? _schedulerStop; private MarketDataService? _market; + private TradingService? _trading; private volatile HostStatus _status = new(HostMode.Starting, null, null, clock.UtcNow, 0); private volatile AppServices? _services; @@ -286,7 +288,11 @@ internal sealed partial class AnubisHost( _market = MarketDataEnabled ? new MarketDataService(_db, clock, bus, settings, secrets, Config.Data, overrides?.MarketHttp, overrides?.MarketSockets, logger) : null; - _services = new AppServices(_db, settings, secrets, access, backups, scheduler, _market); + _trading = TradingEnabled && (identity.File ?? Installation.ReadFile(Config.Data)) is { } file + ? new TradingService(_db, clock, bus, secrets, _market, new FxStore(_db, clock), TradingConsent.From(Config), file.InstallationId, + overrides?.MarketHttp, overrides?.MarketSockets, logger) + : null; + _services = new AppServices(_db, settings, secrets, access, backups, scheduler, _market, _trading); StartScheduler(scheduler, backups); SetStatus(HostMode.Ready, null); } @@ -389,12 +395,20 @@ internal sealed partial class AnubisHost( !options.Demo && overrides?.MarketData != false && environment.GetValueOrDefault("ANUBIS_MARKET_DATA") is not ("0" or "off" or "false"); + /// + /// Accounts and orders: off in demo mode (the demo shows appendix F and sends nothing), when + /// ANUBIS_TRADING is off, and in tests unless they ask for it. + /// + private bool TradingEnabled => + !options.Demo && (overrides is null ? true : overrides.Trading == true) && + environment.GetValueOrDefault("ANUBIS_TRADING") is not ("0" or "off" or "false"); + private void StartScheduler(Scheduler scheduler, Backups backups) { scheduler.Add(new ScheduledJob("backup", "Salvataggio del database", Schedule.Daily(new TimeOnly(3, 30), Config.TimeZone), async ct => await backups.TakeAsync(_db!, "notturno", ct).ConfigureAwait(false)) { MaxLateness = TimeSpan.FromHours(2) }); - foreach (var job in _market?.Jobs() ?? []) + foreach (var job in (_market?.Jobs() ?? []).Concat(_trading?.Jobs() ?? [])) { scheduler.Add(job); } @@ -402,11 +416,13 @@ internal sealed partial class AnubisHost( _schedulerStop = new CancellationTokenSource(); var token = _schedulerStop.Token; var market = _market; + var trading = _trading; _schedulerLoop = Task.Run(async () => { using var runs = bus.Subscribe(); var recorder = RecordJobsAsync(runs, token); var collecting = market is null ? Task.CompletedTask : RunMarketDataAsync(market, token); + var dealing = trading is null ? Task.CompletedTask : RunTradingAsync(trading, token); try { await scheduler.RunAsync(token).ConfigureAwait(false); @@ -416,6 +432,7 @@ internal sealed partial class AnubisHost( } await collecting.ConfigureAwait(false); + await dealing.ConfigureAwait(false); await recorder.ConfigureAwait(false); }, CancellationToken.None); } @@ -435,6 +452,22 @@ internal sealed partial class AnubisHost( } } + private async Task RunTradingAsync(TradingService trading, CancellationToken cancellationToken) + { + try + { + await trading.StartAsync(cancellationToken).ConfigureAwait(false); + await trading.RunAsync(cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + } + catch (Exception ex) + { + LogTradingFailed(logger, ex); + } + } + // The jobs table keeps the outcome of the last run of each job (Diario e sistema, SPEC 13.6). private async Task RecordJobsAsync(EventSubscription runs, CancellationToken cancellationToken) { @@ -488,6 +521,8 @@ internal sealed partial class AnubisHost( _schedulerLoop = null; _market?.Dispose(); _market = null; + _trading?.Dispose(); + _trading = null; } // Values of the startup configuration that also exist as settings are read-only in the interface (SPEC 13.5). @@ -527,6 +562,9 @@ internal sealed partial class AnubisHost( [LoggerMessage(Level = LogLevel.Error, Message = "Market data stopped")] private static partial void LogMarketDataFailed(ILogger logger, Exception exception); + [LoggerMessage(Level = LogLevel.Error, Message = "Trading stopped")] + private static partial void LogTradingFailed(ILogger logger, Exception exception); + [LoggerMessage(Level = LogLevel.Warning, Message = "Could not record the run of job {Job}")] private static partial void LogJobRecordFailed(ILogger logger, Exception exception, string job); } diff --git a/src/Anubis.Server/ServerOptions.cs b/src/Anubis.Server/ServerOptions.cs index fb853e0..668fc75 100644 --- a/src/Anubis.Server/ServerOptions.cs +++ b/src/Anubis.Server/ServerOptions.cs @@ -75,4 +75,7 @@ internal sealed record ServerOverrides public HttpMessageHandler? MarketHttp { get; init; } public Func? MarketSockets { get; init; } + + /// True starts the accounts and the order managers in a test; off by default in tests. + public bool? Trading { get; init; } } diff --git a/src/Anubis/Core/Format.cs b/src/Anubis/Core/Format.cs index 66380c7..a41678a 100644 --- a/src/Anubis/Core/Format.cs +++ b/src/Anubis/Core/Format.cs @@ -44,6 +44,22 @@ public static class Format return withSign && rounded > 0 ? "+" + text : text; } + /// A quantity with the decimals it has, at most eight: 2, 0,0182, 1.250,5. + public static string Quantity(decimal value) + { + var rounded = Math.Round(value, 8, MidpointRounding.AwayFromZero); + var decimals = 0; + while (decimals < 8 && Math.Round(rounded, decimals) != rounded) + { + decimals++; + } + + return Number(rounded, decimals); + } + + /// A price without currency: two decimals from 1 up, more below so small coins keep their digits. + public static string Price(decimal value) => Math.Abs(value) >= 1m ? Number(value, 2) : Quantity(value); + /// An amount with its currency after a non-breaking space: 1.299,84 €, +18,40 €, −26,00 €. public static string Money(decimal value, string currency = "EUR", bool withSign = false, int decimals = 2) => Number(value, decimals, withSign) + NonBreakingSpace + CurrencySymbol(currency); diff --git a/src/Anubis/Core/Ids.cs b/src/Anubis/Core/Ids.cs index 0b2b908..021bcd3 100644 --- a/src/Anubis/Core/Ids.cs +++ b/src/Anubis/Core/Ids.cs @@ -1,3 +1,5 @@ +using System.Buffers.Binary; +using System.Runtime.CompilerServices; using System.Security.Cryptography; namespace Anubis.Core; @@ -5,11 +7,57 @@ namespace Anubis.Core; /// Surrogate keys (SPEC 5.4): UUID version 7, ordered by creation time. public static class Ids { - /// A new UUIDv7 whose time part comes from the injected clock, so ids follow simulated time too. + private sealed class Sequence + { + public readonly Lock Gate = new(); + public long LastMs = long.MinValue; + public int Counter; + } + + private static readonly ConditionalWeakTable _sequences = []; + + /// + /// A new UUIDv7 whose time part comes from the injected clock, so ids follow simulated time too. Ids made with + /// the same clock in the same millisecond still come out in order: the 12 bits after the version are a counter + /// (RFC 9562, method 1). Two lots bought in the same millisecond must keep their order for LIFO and FIFO. + /// public static Guid NewId(IClock clock) { ArgumentNullException.ThrowIfNull(clock); - return Guid.CreateVersion7(clock.UtcNow); + var ms = clock.UtcNow.ToUnixTimeMilliseconds(); + var sequence = _sequences.GetValue(clock, _ => new Sequence()); + int counter; + lock (sequence.Gate) + { + if (ms == sequence.LastMs || (ms < sequence.LastMs && sequence.LastMs - ms < 10)) + { + // Same millisecond, or a clock that stepped back a hair: keep counting from where it was. + ms = sequence.LastMs; + if (++sequence.Counter > 0xFFF) + { + sequence.LastMs = ++ms; + sequence.Counter = 0; + } + } + else + { + // A new millisecond (or a manual clock set elsewhere): start low, leaving room to count. + sequence.LastMs = ms; + sequence.Counter = RandomNumberGenerator.GetInt32(0, 0x800); + } + + counter = sequence.Counter; + } + + Span bytes = stackalloc byte[16]; + RandomNumberGenerator.Fill(bytes); + Span time = stackalloc byte[8]; + BinaryPrimitives.WriteInt64BigEndian(time, ms); + time[2..].CopyTo(bytes); + bytes[6] = (byte)(0x70 | ((counter >> 8) & 0x0F)); + bytes[7] = (byte)(counter & 0xFF); + bytes[8] = (byte)((bytes[8] & 0x3F) | 0x80); + return new Guid(bytes, bigEndian: true); } /// A random token for sessions and fingerprints, URL-safe base64 of 32 bytes. diff --git a/src/Anubis/Db/Migrations/0003_trading.sql b/src/Anubis/Db/Migrations/0003_trading.sql new file mode 100644 index 0000000..7cc7bcd --- /dev/null +++ b/src/Anubis/Db/Migrations/0003_trading.sql @@ -0,0 +1,195 @@ +-- Phase 3 schema (SPEC 7, ADR 0009): orders with their steps and events, a ledger for each strategy and +-- environment, account state, unsellable residues, the internal simulator's own book. + +-- Orders. One row per order sent to a broker: every step of the chasing limit and every re-placed stop is its +-- own row with its own client_order_id; execution_id groups the steps of one execution. +ALTER TABLE orders ADD COLUMN purpose TEXT; +ALTER TABLE orders ADD COLUMN time_in_force TEXT; +ALTER TABLE orders ADD COLUMN post_only {bool}; +ALTER TABLE orders ADD COLUMN reference_price {money}; +ALTER TABLE orders ADD COLUMN filled_quantity {money}; +ALTER TABLE orders ADD COLUMN average_fill_price {money}; +ALTER TABLE orders ADD COLUMN step INTEGER; +ALTER TABLE orders ADD COLUMN reason TEXT; +ALTER TABLE orders ADD COLUMN submitted_at {timestamp}; +ALTER TABLE orders ADD COLUMN closed_at {timestamp}; + +CREATE INDEX orders_account_status ON orders (account_id, status); + +-- One wanted execution: a buy or a sale of a quantity, carried out by one or more orders (the chasing limit, +-- SPEC 7.2). It survives a restart: the order manager picks it up where it stopped. +CREATE TABLE executions ( + id {uuid} PRIMARY KEY, + account_id {uuid} NOT NULL REFERENCES accounts (id), + instrument_id {uuid} NOT NULL REFERENCES instruments (id), + strategy TEXT NOT NULL, + side TEXT NOT NULL, + purpose TEXT NOT NULL, + quantity {money} NOT NULL, + filled {money} NOT NULL, + order_key TEXT NOT NULL, + sequence INTEGER NOT NULL, + step INTEGER NOT NULL, + reference_price {money}, + tolerance {money}, + stop_level {money}, + status TEXT NOT NULL, + reason TEXT, + started_at {timestamp} NOT NULL, + step_started_at {timestamp}, + alerted_at {timestamp}, + finished_at {timestamp}, + created_at {timestamp} NOT NULL, + updated_at {timestamp} NOT NULL +){strict}; + +CREATE INDEX executions_account_status ON executions (account_id, status); + +ALTER TABLE orders ADD COLUMN execution_id {uuid}; + +CREATE INDEX orders_execution ON orders (execution_id); + +-- Every change of state of an order (SPEC 7.2). Append-only. +CREATE TABLE order_events ( + id {uuid} PRIMARY KEY, + order_id {uuid} NOT NULL REFERENCES orders (id), + from_status TEXT, + to_status TEXT NOT NULL, + filled_quantity {money}, + note TEXT, + occurred_at {timestamp} NOT NULL, + created_at {timestamp} NOT NULL +){strict}; + +CREATE INDEX order_events_order ON order_events (order_id, occurred_at); + +-- Fills belong to a strategy; the reference price and the slippage are measured for each one (SPEC 7.2). +ALTER TABLE fills ADD COLUMN strategy TEXT; +ALTER TABLE fills ADD COLUMN reference_price {money}; +ALTER TABLE fills ADD COLUMN slippage_bp {money}; + +-- Lots: a buy opens one (positive quantity); a sell consumes open lots in the tax order, one negative row each, +-- closes_id pointing at the consumed lot (SPEC 7.5). +ALTER TABLE lots ADD COLUMN closes_id {uuid}; + +-- The ledger of a strategy in an account (one account = one environment): every row says whose money it is. +ALTER TABLE cash_ledger ADD COLUMN strategy TEXT; + +CREATE INDEX cash_ledger_owner ON cash_ledger (account_id, strategy); + +-- Share of the broker's entrusted capital (SPEC 7.1, 8.6), between 0 and 1. +ALTER TABLE strategy_state ADD COLUMN share {money}; + +-- Equity snapshots carry the world they belong to: simulated money and real money never mix (SPEC 7.1). +ALTER TABLE equity_snapshots ADD COLUMN world TEXT; +ALTER TABLE equity_snapshots ADD COLUMN currency TEXT; + +-- Net capital flows up to the snapshot, and the time-weighted index they leave behind (SPEC 7.5): a deposit is +-- never a gain. The peak of the index gives the drawdown; the FX effect is the part of a dollar result due to EUR/USD. +ALTER TABLE equity_snapshots ADD COLUMN flows {money}; +ALTER TABLE equity_snapshots ADD COLUMN twr_index {money}; +ALTER TABLE equity_snapshots ADD COLUMN peak_index {money}; +ALTER TABLE equity_snapshots ADD COLUMN fx_effect {money}; + +CREATE INDEX equity_snapshots_owner ON equity_snapshots (scope, world, account_id, strategy, taken_at); + +-- Capital entrusted for each broker, in euro, converted on the day it is set (SPEC 7.1). Append-only history: +-- the latest row of a broker is the current figure. +CREATE TABLE capital_changes ( + id {uuid} PRIMARY KEY, + broker TEXT NOT NULL, + amount_eur {money} NOT NULL, + currency TEXT NOT NULL, + fx_rate {money} NOT NULL, + amount {money} NOT NULL, + changed_by TEXT NOT NULL, + created_at {timestamp} NOT NULL +){strict}; + +CREATE INDEX capital_changes_broker ON capital_changes (broker, created_at); + +-- A trade runs from quantity zero to quantity zero for an instrument and a strategy (SPEC 7.5). Derived from +-- the fills, so it may be updated while it is open. +CREATE TABLE trades ( + id {uuid} PRIMARY KEY, + account_id {uuid} NOT NULL REFERENCES accounts (id), + instrument_id {uuid} NOT NULL REFERENCES instruments (id), + strategy TEXT NOT NULL, + status TEXT NOT NULL, + opened_at {timestamp} NOT NULL, + closed_at {timestamp}, + bought_quantity {money} NOT NULL, + bought_value {money} NOT NULL, + sold_quantity {money} NOT NULL, + sold_value {money} NOT NULL, + fees {money} NOT NULL, + realized {money} NOT NULL, + exit_reason TEXT, + created_at {timestamp} NOT NULL, + updated_at {timestamp} NOT NULL +){strict}; + +CREATE INDEX trades_owner ON trades (account_id, strategy, instrument_id, status); + +-- Quantities left on an account after a complete exit, below the lot or the minimum: written off the ledger at +-- market value and listed apart on the Conti screen (SPEC 7.2). +CREATE TABLE residues ( + id {uuid} PRIMARY KEY, + account_id {uuid} NOT NULL REFERENCES accounts (id), + instrument_id {uuid} NOT NULL REFERENCES instruments (id), + strategy TEXT NOT NULL, + quantity {money} NOT NULL, + value {money} NOT NULL, + currency TEXT NOT NULL, + reason TEXT NOT NULL, + created_at {timestamp} NOT NULL +){strict}; + +-- State of each account: prudent mode after an unexplained difference (SPEC 7.4), last reconciliation, what the +-- key may do (never withdraw: SPEC 2.2). +CREATE TABLE account_status ( + id {uuid} PRIMARY KEY, + account_id {uuid} NOT NULL UNIQUE REFERENCES accounts (id), + mode TEXT NOT NULL, + mode_since {timestamp}, + mode_reason TEXT, + differences {json}, + last_reconciled_at {timestamp}, + last_outcome TEXT, + key_can_trade {bool}, + key_can_withdraw {bool}, + key_checked_at {timestamp}, + created_at {timestamp} NOT NULL, + updated_at {timestamp} NOT NULL +){strict}; + +-- Outcome of every reconciliation, for the diary and the review. Append-only. +CREATE TABLE reconciliations ( + id {uuid} PRIMARY KEY, + account_id {uuid} NOT NULL REFERENCES accounts (id), + outcome TEXT NOT NULL, + details {json} NOT NULL, + occurred_at {timestamp} NOT NULL, + created_at {timestamp} NOT NULL +){strict}; + +CREATE INDEX reconciliations_account ON reconciliations (account_id, occurred_at); + +-- Corporate actions already applied to an account's ledger and stops (SPEC 6.10): never applied twice. +CREATE TABLE applied_actions ( + id {uuid} PRIMARY KEY, + account_id {uuid} NOT NULL REFERENCES accounts (id), + source_key TEXT NOT NULL, + created_at {timestamp} NOT NULL, + UNIQUE (account_id, source_key) +){strict}; + +-- The internal simulator's own book (SPEC 7.3): balances, positions, open orders, its last look at prices. +CREATE TABLE simulator_books ( + id {uuid} PRIMARY KEY, + account_id {uuid} NOT NULL UNIQUE REFERENCES accounts (id), + book {json} NOT NULL, + seen_until {timestamp} NOT NULL, + created_at {timestamp} NOT NULL, + updated_at {timestamp} NOT NULL +){strict}; diff --git a/src/Anubis/Trading/AlpacaTrading.cs b/src/Anubis/Trading/AlpacaTrading.cs new file mode 100644 index 0000000..990650a --- /dev/null +++ b/src/Anubis/Trading/AlpacaTrading.cs @@ -0,0 +1,451 @@ +using System.Globalization; +using System.Net; +using System.Runtime.CompilerServices; +using System.Text.Json; +using Anubis.Brokers; +using Anubis.Core; +using Anubis.Data; + +namespace Anubis.Trading; + +/// Addresses of Alpaca's trading API for an environment (SPEC 4.1, API-NOTES). +public sealed record AlpacaTradingOptions +{ + public required string Environment { get; init; } + + public Uri RestUrl => Environment == TradingEnvironments.Live ? new("https://api.alpaca.markets") : new("https://paper-api.alpaca.markets"); + + public Uri StreamUrl => Environment == TradingEnvironments.Live ? new("wss://api.alpaca.markets/stream") : new("wss://paper-api.alpaca.markets/stream"); +} + +/// +/// The account side of Alpaca (SPEC 4.1, 5.3): orders, positions, fills from the account activities, the +/// trade_updates stream. The paper account in development; a live account only with the startup consent. +/// Fills enter the ledger only from the activities, so the stream and the query never record one twice. +/// +public sealed class AlpacaTrading : IBrokerAccount +{ + private readonly TradingHttp _http; + private readonly IClock _clock; + private readonly AlpacaCredentials _credentials; + private readonly AlpacaTradingOptions _options; + private readonly Func _sockets; + private readonly RateLimiter _limiter; + + public AlpacaTrading(HttpClient http, IClock clock, AlpacaCredentials credentials, AlpacaTradingOptions options, TradingConsent consent, Func? sockets = null) + { + ArgumentNullException.ThrowIfNull(options); + LiveGuard.Ensure(options.Environment, consent); + if (options.Environment == TradingEnvironments.Simulation) + { + throw new ArgumentException("Il simulatore interno non passa da Alpaca.", nameof(options)); + } + + _http = new TradingHttp(http, clock, "Alpaca"); + _clock = clock; + _credentials = credentials ?? throw new ArgumentNullException(nameof(credentials)); + _options = options; + _sockets = sockets ?? (() => new ClientWebSocketTransport()); + + // 200 requests a minute for the whole key, shared with the data client: keep well under it. + _limiter = new RateLimiter(clock, 120, TimeSpan.FromMinutes(1)); + } + + public string Venue => Venues.Alpaca; + + public string Environment => _options.Environment; + + public BrokerCapabilities Capabilities { get; } = new() + { + Fractional = true, + FractionalStopsAreDayOnly = true, + OppositeSideBlocked = true, + }; + + public async Task ServerTimeAsync(CancellationToken cancellationToken) + { + using var json = await GetJsonAsync("/v2/clock", cancellationToken).ConfigureAwait(false); + return DateTimeOffset.Parse(json.RootElement.GetProperty("timestamp").GetString()!, CultureInfo.InvariantCulture).ToUniversalTime(); + } + + public async Task GetAccountAsync(CancellationToken cancellationToken) + { + using var json = await GetJsonAsync("/v2/account", cancellationToken).ConfigureAwait(false); + var root = json.RootElement; + var currency = Text(root, "currency") ?? "USD"; + return new AccountSnapshot(currency, Number(root, "equity") ?? 0m, new Dictionary { [currency] = Number(root, "cash") ?? 0m }, _clock.UtcNow) + { + BuyingPower = Number(root, "non_marginable_buying_power") ?? Number(root, "buying_power"), + }; + } + + public async Task> GetPositionsAsync(CancellationToken cancellationToken) + { + using var json = await GetJsonAsync("/v2/positions", cancellationToken).ConfigureAwait(false); + return json.RootElement.EnumerateArray() + .Select(p => new BrokerPosition(Text(p, "symbol")!, Number(p, "qty") ?? 0m, Number(p, "avg_entry_price"))) + .ToList(); + } + + public async Task> GetOpenOrdersAsync(CancellationToken cancellationToken) + { + using var json = await GetJsonAsync("/v2/orders?status=open&limit=500&direction=asc", cancellationToken).ConfigureAwait(false); + return json.RootElement.EnumerateArray().Select(ReadOrder).ToList(); + } + + public async Task SubmitOrderAsync(OrderRequest request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + var body = OrderBody(request); + var url = new Uri(_options.RestUrl, "/v2/orders"); + var answer = await _http.SendAsync(HttpMethod.Post, url, body, _ => Headers(), _limiter, retry: false, cancellationToken).ConfigureAwait(false); + if (answer.Ok) + { + using var json = JsonDocument.Parse(answer.Body); + return ReadOrder(json.RootElement); + } + + var (code, message) = Error(answer.Body); + if (answer.Status == HttpStatusCode.UnprocessableEntity && message.Contains("client_order_id must be unique", StringComparison.OrdinalIgnoreCase)) + { + // The broker already has this id: the earlier send arrived. Idempotent, as SPEC 5.3 asks. + return await GetOrderAsync(request.ClientOrderId, request.Symbol, cancellationToken).ConfigureAwait(false) + ?? throw new OrderRejectedException("Alpaca: identificativo già usato da un altro ordine.", "duplicate_client_order_id"); + } + + throw new OrderRejectedException($"Alpaca: ordine {request.ClientOrderId} rifiutato ({(int)answer.Status} {code}): {Redactor.Redact(message)}", RejectionCode(answer.Status, message)); + } + + public async Task CancelOrderAsync(string clientOrderId, string symbol, CancellationToken cancellationToken) + { + var order = await GetOrderAsync(clientOrderId, symbol, cancellationToken).ConfigureAwait(false); + if (order?.BrokerOrderId is null || !order.IsOpen) + { + return; + } + + var url = new Uri(_options.RestUrl, "/v2/orders/" + Uri.EscapeDataString(order.BrokerOrderId)); + var answer = await _http.SendAsync(HttpMethod.Delete, url, null, _ => Headers(), _limiter, retry: true, cancellationToken).ConfigureAwait(false); + + // 204: accepted (the order may stay pending_cancel for a while); 422: not cancelable any more; 404: unknown. + if (!answer.Ok && answer.Status is not (HttpStatusCode.UnprocessableEntity or HttpStatusCode.NotFound)) + { + throw _http.Failure(url, answer); + } + } + + public async Task GetOrderAsync(string clientOrderId, string symbol, CancellationToken cancellationToken) + { + var url = new Uri(_options.RestUrl, "/v2/orders:by_client_order_id?client_order_id=" + Uri.EscapeDataString(clientOrderId)); + var answer = await _http.SendAsync(HttpMethod.Get, url, null, _ => Headers(), _limiter, retry: true, cancellationToken).ConfigureAwait(false); + if (answer.Status is HttpStatusCode.NotFound or HttpStatusCode.UnprocessableEntity) + { + return null; + } + + if (!answer.Ok) + { + throw _http.Failure(url, answer); + } + + using var json = JsonDocument.Parse(answer.Body); + return ReadOrder(json.RootElement); + } + + /// Fills from the FILL activities; the order's client id comes from the orders of the same period. + public async Task> GetFillsAsync(DateTimeOffset since, CancellationToken cancellationToken) + { + var activities = await ActivitiesAsync("FILL", since, cancellationToken).ConfigureAwait(false); + if (activities.Count == 0) + { + return []; + } + + var clientIds = new Dictionary(StringComparer.Ordinal); + using (var orders = await GetJsonAsync("/v2/orders?status=all&limit=500&direction=asc&after=" + Uri.EscapeDataString(Iso(since.AddDays(-1))), cancellationToken).ConfigureAwait(false)) + { + foreach (var order in orders.RootElement.EnumerateArray()) + { + clientIds[Text(order, "id")!] = Text(order, "client_order_id") ?? ""; + } + } + + var fills = new List(); + foreach (var activity in activities) + { + var orderId = Text(activity, "order_id") ?? ""; + if (!clientIds.TryGetValue(orderId, out var clientId)) + { + using var order = await GetJsonAsync("/v2/orders/" + Uri.EscapeDataString(orderId), cancellationToken).ConfigureAwait(false); + clientId = Text(order.RootElement, "client_order_id") ?? ""; + } + + fills.Add(ReadFill(activity, clientId)); + } + + return fills; + } + + public async Task> GetCashActivitiesAsync(DateTimeOffset since, CancellationToken cancellationToken) + { + var activities = await ActivitiesAsync("DIV,DIVNRA,FEE,CSD,CSW", since, cancellationToken).ConfigureAwait(false); + return activities.Select(ReadCashActivity).ToList(); + } + + /// + /// Alpaca documents no key scopes and no way to read them (API-NOTES): the key can read and trade if the account + /// answers and is not blocked. The trading API has no cash withdrawal; crypto withdrawals are not used. + /// + public async Task GetKeyPermissionsAsync(CancellationToken cancellationToken) + { + using var json = await GetJsonAsync("/v2/account", cancellationToken).ConfigureAwait(false); + var root = json.RootElement; + var blocked = Flag(root, "trading_blocked") || Flag(root, "account_blocked"); + return new KeyPermissions(true, !blocked && Text(root, "status") == "ACTIVE", false, + "Alpaca non dichiara i permessi delle chiavi: l'API di trading non preleva denaro. " + (blocked ? "Il conto risulta bloccato." : "Il conto può operare.")); + } + + public async IAsyncEnumerable StreamOrderUpdatesAsync([EnumeratorCancellation] CancellationToken cancellationToken) + { + await using var socket = _sockets(); + await socket.ConnectAsync(_options.StreamUrl, null, cancellationToken).ConfigureAwait(false); + await socket.SendAsync(JsonSerializer.Serialize(new { action = "auth", key = _credentials.KeyId, secret = _credentials.Secret }), cancellationToken).ConfigureAwait(false); + var listening = false; + while (await socket.ReceiveAsync(cancellationToken).ConfigureAwait(false) is { } message) + { + using var json = JsonDocument.Parse(message); + var root = json.RootElement; + var stream = Text(root, "stream"); + if (stream == "authorization") + { + if (root.GetProperty("data").GetProperty("status").GetString() != "authorized") + { + throw new BrokerException("Alpaca: flusso degli ordini non autorizzato, controlla le chiavi.", retryable: false); + } + + await socket.SendAsync("""{"action":"listen","data":{"streams":["trade_updates"]}}""", cancellationToken).ConfigureAwait(false); + continue; + } + + if (stream == "listening") + { + listening = true; + continue; + } + + if (listening && stream == "trade_updates" && ParseTradeUpdate(root.GetProperty("data")) is { } update) + { + yield return update; + } + } + } + + /// One trade_updates message: the order, and the execution for fill and partial_fill events. + public static OrderUpdate? ParseTradeUpdate(JsonElement data) + { + if (!data.TryGetProperty("order", out var orderElement)) + { + return null; + } + + var order = ReadOrder(orderElement); + var @event = Text(data, "event"); + BrokerFill? fill = null; + if (@event is "fill" or "partial_fill" && Number(data, "qty") is { } qty && Number(data, "price") is { } price) + { + var at = DateTimeOffset.Parse(Text(data, "timestamp")!, CultureInfo.InvariantCulture).ToUniversalTime(); + fill = new BrokerFill(Text(data, "execution_id") ?? (order.BrokerOrderId + ":" + Text(data, "timestamp")), order.ClientOrderId, order.Symbol, order.Side, qty, price, 0m, "USD", at); + } + + return new OrderUpdate(order, fill); + } + + public static BrokerOrder ReadOrder(JsonElement o) + { + var filled = Number(o, "filled_qty") ?? 0m; + var status = Text(o, "status") switch + { + "filled" => OrderStatus.Filled, + "partially_filled" => OrderStatus.PartiallyFilled, + "canceled" or "replaced" => OrderStatus.Canceled, + "expired" => OrderStatus.Expired, + "rejected" => OrderStatus.Rejected, + _ when filled > 0m => OrderStatus.PartiallyFilled, + _ => OrderStatus.Submitted, + }; + var kind = (Text(o, "type") ?? Text(o, "order_type")) switch + { + "market" => OrderKind.Market, + "stop" => OrderKind.Stop, + _ => OrderKind.Limit, + }; + return new BrokerOrder( + Text(o, "client_order_id") ?? "", + Text(o, "id"), + Text(o, "symbol") ?? "", + Text(o, "side") == "sell" ? OrderSide.Sell : OrderSide.Buy, + kind, + Number(o, "qty") ?? 0m, + status, + filled, + DateTimeOffset.Parse(Text(o, "updated_at") ?? Text(o, "created_at")!, CultureInfo.InvariantCulture).ToUniversalTime()) + { + LimitPrice = Number(o, "limit_price"), + StopPrice = Number(o, "stop_price"), + TimeInForce = Text(o, "time_in_force") == "gtc" ? TimeInForce.Gtc : Text(o, "time_in_force") == "ioc" ? TimeInForce.Ioc : TimeInForce.Day, + AverageFillPrice = Number(o, "filled_avg_price"), + Reason = Text(o, "status") is "rejected" or "canceled" or "expired" ? Text(o, "status") : null, + }; + } + + public static BrokerFill ReadFill(JsonElement a, string clientOrderId) => new( + Text(a, "id")!, + clientOrderId, + Text(a, "symbol")!, + Text(a, "side") == "sell" ? OrderSide.Sell : OrderSide.Buy, + Number(a, "qty") ?? 0m, + Number(a, "price") ?? 0m, + 0m, + "USD", + DateTimeOffset.Parse(Text(a, "transaction_time")!, CultureInfo.InvariantCulture).ToUniversalTime()); + + public static CashActivity ReadCashActivity(JsonElement a) + { + var type = Text(a, "activity_type"); + var kind = type switch + { + "DIV" or "DIVNRA" => CashActivityKinds.Dividend, + "FEE" => CashActivityKinds.Fee, + "CSD" => CashActivityKinds.Deposit, + "CSW" => CashActivityKinds.Withdrawal, + _ => CashActivityKinds.Other, + }; + var when = Text(a, "transaction_time") ?? Text(a, "date") + "T00:00:00Z"; + return new CashActivity(Text(a, "id")!, kind, Number(a, "net_amount") ?? 0m, Text(a, "currency") ?? "USD", + DateTimeOffset.Parse(when, CultureInfo.InvariantCulture).ToUniversalTime()) + { Symbol = Text(a, "symbol") }; + } + + /// The JSON body of an order: numbers as strings, as Alpaca documents them. + public static string OrderBody(OrderRequest request) + { + ArgumentNullException.ThrowIfNull(request); + var body = new Dictionary + { + ["symbol"] = request.Symbol, + ["qty"] = Wire.Number(request.Quantity), + ["side"] = Wire.Text(request.Side), + ["type"] = Wire.Text(request.Kind), + ["time_in_force"] = Wire.Text(request.TimeInForce), + ["client_order_id"] = request.ClientOrderId, + }; + if (request.LimitPrice is { } limit) + { + body["limit_price"] = Wire.Number(limit); + } + + if (request.StopPrice is { } stop) + { + body["stop_price"] = Wire.Number(stop); + } + + return JsonSerializer.Serialize(body); + } + + private static string RejectionCode(HttpStatusCode status, string message) + { + if (message.Contains("wash trade", StringComparison.OrdinalIgnoreCase) || message.Contains("opposite side", StringComparison.OrdinalIgnoreCase)) + { + return "opposite_side_order_open"; + } + + if (message.Contains("insufficient", StringComparison.OrdinalIgnoreCase) || message.Contains("not sufficient", StringComparison.OrdinalIgnoreCase)) + { + return "insufficient"; + } + + if (message.Contains("fractional", StringComparison.OrdinalIgnoreCase)) + { + return "fractional_rule"; + } + + return status == HttpStatusCode.Forbidden ? "forbidden" : "invalid"; + } + + private async Task> ActivitiesAsync(string types, DateTimeOffset since, CancellationToken cancellationToken) + { + var result = new List(); + string? token = null; + for (var page = 0; page < 50; page++) + { + var path = $"/v2/account/activities?activity_types={types}&direction=asc&page_size=100&after={Uri.EscapeDataString(Iso(since))}" + + (token is null ? "" : "&page_token=" + Uri.EscapeDataString(token)); + using var json = await GetJsonAsync(path, cancellationToken).ConfigureAwait(false); + var items = json.RootElement.EnumerateArray().Select(e => e.Clone()).ToList(); + result.AddRange(items); + if (items.Count < 100) + { + break; + } + + token = Text(items[^1], "id"); + } + + return result; + } + + private async Task GetJsonAsync(string pathAndQuery, CancellationToken cancellationToken) + { + var url = new Uri(_options.RestUrl, pathAndQuery); + var answer = await _http.SendAsync(HttpMethod.Get, url, null, _ => Headers(), _limiter, retry: true, cancellationToken).ConfigureAwait(false); + if (!answer.Ok) + { + throw _http.Failure(url, answer); + } + + return JsonDocument.Parse(answer.Body); + } + + private Dictionary Headers() => new() + { + ["APCA-API-KEY-ID"] = _credentials.KeyId, + ["APCA-API-SECRET-KEY"] = _credentials.Secret, + }; + + private static (string Code, string Message) Error(string body) + { + try + { + using var json = JsonDocument.Parse(body); + var root = json.RootElement; + var code = root.TryGetProperty("code", out var c) ? c.ToString() : ""; + return (code, Text(root, "message") ?? body); + } + catch (JsonException) + { + return ("", body); + } + } + + private static string Iso(DateTimeOffset at) => at.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture); + + private static string? Text(JsonElement e, string name) => + e.ValueKind == JsonValueKind.Object && e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null; + + private static bool Flag(JsonElement e, string name) => e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.True; + + private static decimal? Number(JsonElement e, string name) + { + if (e.ValueKind != JsonValueKind.Object || !e.TryGetProperty(name, out var v)) + { + return null; + } + + return v.ValueKind switch + { + JsonValueKind.String when decimal.TryParse(v.GetString(), NumberStyles.Float, CultureInfo.InvariantCulture, out var d) => d, + JsonValueKind.Number => v.GetDecimal(), + _ => null, + }; + } +} diff --git a/src/Anubis/Trading/Capital.cs b/src/Anubis/Trading/Capital.cs new file mode 100644 index 0000000..4f1bf63 --- /dev/null +++ b/src/Anubis/Trading/Capital.cs @@ -0,0 +1,175 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; + +namespace Anubis.Trading; + +/// The three base strategies, their broker and their default share of its capital (SPEC 8.6). +public static class Strategies +{ + public const string CryptoTrend = "crypto_trend"; + public const string EquityMomentum = "equity_momentum"; + public const string EquityMeanrev = "equity_meanrev"; + + public static readonly IReadOnlyList<(string Name, string Broker, decimal Share)> Base = + [ + (CryptoTrend, Venues.Okx, 1m), + (EquityMomentum, Venues.Alpaca, 0.75m), + (EquityMeanrev, Venues.Alpaca, 0.25m), + ]; + + public static string BrokerOf(string strategy) => + Base.FirstOrDefault(b => b.Name == strategy).Broker ?? throw new ArgumentException($"Unknown strategy '{strategy}'.", nameof(strategy)); + + /// The currency a broker's ledger is kept in: euro on OKX Europe, dollars on Alpaca (SPEC 7.1). + public static string CurrencyOf(string broker) => broker == Venues.Alpaca ? "USD" : "EUR"; + + /// Stages of SPEC 12.3. Phase 3 has no backtests yet, so every base strategy starts in observation. + public const string Observation = "observation"; +} + +public sealed record EntrustedCapital(string Broker, decimal AmountEur, string Currency, decimal FxRate, decimal Amount, string ChangedBy, DateTimeOffset At); + +public sealed record StrategyCapital(string Strategy, Guid AccountId, string Currency, decimal Share, decimal Capital, decimal Cash); + +public sealed class CapitalException : Exception +{ + public CapitalException() + { + } + + public CapitalException(string message) + : base(message) + { + } + + public CapitalException(string message, Exception inner) + : base(message, inner) + { + } +} + +/// +/// Capital entrusted to the bot (SPEC 7.1, 8.6): one figure in euro for each broker, set only by the user, split +/// between the broker's strategies by their shares. A dollar account converts it at the day's rate and keeps its +/// ledger in dollars from then on. Every change reaches the ledgers as a capital flow, so it is never a result. +/// +public sealed class Capital(Database db, IClock clock, Ledger ledger, FxStore fx) +{ + public Task EntrustedAsync(string broker, CancellationToken cancellationToken) => + db.ReadAsync(s => s.FirstOrDefaultAsync( + "SELECT broker, amount_eur, currency, fx_rate, amount, changed_by, created_at FROM capital_changes WHERE broker = @b ORDER BY created_at DESC, id DESC LIMIT 1", + r => new EntrustedCapital(r.Text("broker"), r.Money("amount_eur"), r.Text("currency"), r.Money("fx_rate"), r.Money("amount"), r.Text("changed_by"), r.Moment("created_at")), + ("b", broker)), cancellationToken); + + /// The broker's strategies with their share, the capital given so far and their cash, in the account's currency. + public async Task> StrategiesAsync(string broker, CancellationToken cancellationToken) + { + var rows = await db.ReadAsync(s => s.QueryAsync( + "SELECT st.strategy, st.account_id, st.share, a.base_currency FROM strategy_state st JOIN accounts a ON a.id = st.account_id WHERE a.broker = @b ORDER BY st.strategy", + r => (Strategy: r.Text("strategy"), Account: r.Id("account_id"), Share: r.MoneyOrNull("share"), Currency: r.Text("base_currency")), ("b", broker)), cancellationToken) + .ConfigureAwait(false); + var given = await db.ReadAsync(s => s.QueryAsync("SELECT account_id, strategy, amount FROM cash_ledger WHERE kind = @k AND strategy IS NOT NULL", + r => (Account: r.Id("account_id"), Strategy: r.Text("strategy"), Amount: r.Money("amount")), ("k", LedgerKinds.Capital)), cancellationToken).ConfigureAwait(false); + var equities = await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false); + return rows.Select(r => new StrategyCapital(r.Strategy, r.Account, r.Currency, + r.Share ?? Strategies.Base.FirstOrDefault(b => b.Name == r.Strategy).Share, + given.Where(g => g.Account == r.Account && g.Strategy == r.Strategy).Sum(g => g.Amount), + equities.Where(e => e.AccountId == r.Account && e.Strategy == r.Strategy).Sum(e => e.Cash))).ToList(); + } + + /// Sets the capital entrusted for a broker, in euro, and gives each strategy its share. + public async Task SetAsync(string broker, decimal amountEur, string changedBy, CancellationToken cancellationToken) + { + if (amountEur < 0m) + { + throw new CapitalException("Il capitale affidato non può essere negativo."); + } + + var currency = Strategies.CurrencyOf(broker); + var rate = 1m; + if (currency != "EUR") + { + var today = DateOnly.FromDateTime(clock.UtcNow.UtcDateTime); + rate = (await fx.RateOnAsync("EUR", currency, today, cancellationToken).ConfigureAwait(false) + ?? await fx.LatestAsync("EUR", currency, cancellationToken).ConfigureAwait(false))?.Rate + ?? throw new CapitalException($"Manca il cambio EUR/{currency}: lo scarico ogni giorno dalla BCE, riprova più tardi."); + } + + var entrusted = new EntrustedCapital(broker, amountEur, currency, rate, Math.Round(amountEur * rate, 2, MidpointRounding.ToZero), changedBy, clock.UtcNow); + var plan = await PlanAsync(broker, entrusted.Amount, null, cancellationToken).ConfigureAwait(false); + await db.WriteAsync(s => s.ExecuteAsync( + "INSERT INTO capital_changes (id, broker, amount_eur, currency, fx_rate, amount, changed_by, created_at) VALUES (@id, @b, @e, @c, @r, @a, @by, @now)", cancellationToken, + ("id", Ids.NewId(clock)), ("b", broker), ("e", amountEur), ("c", currency), ("r", rate), ("a", entrusted.Amount), ("by", changedBy), ("now", entrusted.At)), + cancellationToken).ConfigureAwait(false); + await ApplyAsync(plan, entrusted, cancellationToken).ConfigureAwait(false); + return entrusted; + } + + /// Changes the shares of a broker's strategies (each between 0 and 1, together exactly 1). Never automatic. + public async Task SetSharesAsync(string broker, IReadOnlyDictionary shares, string changedBy, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(shares); + if (shares.Values.Any(v => v is < 0m or > 1m) || shares.Values.Sum() != 1m) + { + throw new CapitalException("Le quote vanno da 0 a 100% e insieme fanno 100%."); + } + + var entrusted = await EntrustedAsync(broker, cancellationToken).ConfigureAwait(false); + var plan = await PlanAsync(broker, entrusted?.Amount ?? 0m, shares, cancellationToken).ConfigureAwait(false); + await db.WriteAsync(async s => + { + foreach (var (strategy, share) in shares) + { + await s.ExecuteAsync("UPDATE strategy_state SET share = @sh, updated_at = @now WHERE strategy = @s", cancellationToken, + ("sh", share), ("now", clock.UtcNow), ("s", strategy)).ConfigureAwait(false); + } + + await Diary.WriteAsync(s, clock, DiaryKinds.System, "shares_changed", + $"Quote di {broker} cambiate da {changedBy}: " + string.Join(", ", shares.Select(p => $"{p.Key} {Format.Quantity(p.Value * 100m)}%")) + ".", null, cancellationToken) + .ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + if (entrusted is not null) + { + await ApplyAsync(plan, entrusted, cancellationToken).ConfigureAwait(false); + } + } + + // What each strategy should have and what that changes. A reduction that would leave a strategy's cash below + // zero is refused: the money is in positions, and the bot never sells to give capital back. + private async Task> PlanAsync(string broker, decimal amount, IReadOnlyDictionary? shares, + CancellationToken cancellationToken) + { + var plan = new List<(StrategyCapital, decimal, decimal)>(); + foreach (var strategy in await StrategiesAsync(broker, cancellationToken).ConfigureAwait(false)) + { + var share = shares?.GetValueOrDefault(strategy.Strategy, strategy.Share) ?? strategy.Share; + var target = Math.Round(amount * share, 2, MidpointRounding.ToZero); + var delta = target - strategy.Capital; + if (strategy.Cash + delta < 0m) + { + throw new CapitalException( + $"{strategy.Strategy} ha investito in posizioni più di quanto resterebbe: potrò ridurre il suo capitale quando avrà venduto. Liquidità ora: {Format.Quantity(strategy.Cash)} {strategy.Currency}."); + } + + plan.Add((strategy, target, delta)); + } + + return plan; + } + + private async Task ApplyAsync(List<(StrategyCapital Strategy, decimal Target, decimal Delta)> plan, EntrustedCapital entrusted, CancellationToken cancellationToken) + { + foreach (var (strategy, target, delta) in plan) + { + if (delta != 0m) + { + await ledger.RecordCapitalAsync(strategy.AccountId, strategy.Strategy, delta, strategy.Currency, + $"Capitale affidato {Format.Quantity(entrusted.AmountEur)} EUR, quota {Format.Quantity(target)} {strategy.Currency}", cancellationToken).ConfigureAwait(false); + } + + await db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET capital = @c, updated_at = @now WHERE strategy = @s", cancellationToken, + ("c", target), ("now", clock.UtcNow), ("s", strategy.Strategy)), cancellationToken).ConfigureAwait(false); + } + } +} diff --git a/src/Anubis/Trading/Diary.cs b/src/Anubis/Trading/Diary.cs new file mode 100644 index 0000000..451d8db --- /dev/null +++ b/src/Anubis/Trading/Diary.cs @@ -0,0 +1,37 @@ +using System.Text.Json; +using Anubis.Core; +using Anubis.Db; + +namespace Anubis.Trading; + +/// Kinds of diary entries, as the Diario screen shows them (SPEC 13.6). +public static class DiaryKinds +{ + public const string Orders = "Ordini"; + public const string System = "Sistema"; +} + +/// +/// The bot's diary and its notices (SPEC 13.6): short sentences in Italian, in the first person. A notice is also +/// queued for Telegram; the sender arrives with Phase 6, the queue is kept from now. +/// +public static class Diary +{ + public static Task WriteAsync(DbSession s, IClock clock, string kind, string code, string message, object? data = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(s); + ArgumentNullException.ThrowIfNull(clock); + var now = clock.UtcNow; + return s.ExecuteAsync("INSERT INTO journal (id, occurred_at, kind, code, message, data, created_at) VALUES (@id, @at, @k, @c, @m, @d, @at)", cancellationToken, + ("id", Ids.NewId(clock)), ("at", now), ("k", kind), ("c", code), ("m", message), ("d", data is null ? null : new DbJson(JsonSerializer.Serialize(data)))); + } + + public static async Task NotifyAsync(DbSession s, IClock clock, string code, string message, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(s); + ArgumentNullException.ThrowIfNull(clock); + await WriteAsync(s, clock, DiaryKinds.System, code, message, null, cancellationToken).ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO notifications (id, channel, kind, message, status, created_at) VALUES (@id, 'telegram', @k, @m, 'pending', @at)", cancellationToken, + ("id", Ids.NewId(clock)), ("k", code), ("m", message), ("at", clock.UtcNow)).ConfigureAwait(false); + } +} diff --git a/src/Anubis/Trading/Equity.cs b/src/Anubis/Trading/Equity.cs new file mode 100644 index 0000000..370de17 --- /dev/null +++ b/src/Anubis/Trading/Equity.cs @@ -0,0 +1,151 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; + +namespace Anubis.Trading; + +/// Real money and simulated money are always kept apart (SPEC 7.1). +public static class Worlds +{ + public const string Real = "real"; + public const string Simulated = "simulated"; +} + +/// Returns corrected for flows (SPEC 7.5): a deposit must never look like a gain. +public static class Returns +{ + /// + /// One period of the time-weighted return: the flow arrives at the start of the period, so the first capital, + /// given to an empty ledger, is not a gain. + /// + public static decimal Step(decimal previousEquity, decimal equity, decimal flow) + { + var start = previousEquity + flow; + return start <= 0m ? 1m : equity / start; + } + + /// Time-weighted return over points carrying equity and cumulative flows: 0.05 is +5%. + public static decimal TimeWeighted(IReadOnlyList<(decimal Equity, decimal Flows)> points) + { + ArgumentNullException.ThrowIfNull(points); + var index = 1m; + for (var i = 1; i < points.Count; i++) + { + index *= Step(points[i - 1].Equity, points[i].Equity, points[i].Flows - points[i - 1].Flows); + } + + return index - 1m; + } + + /// + /// The part of a dollar account's result in euro that is due to EUR/USD alone (SPEC 7.5): every dollar given at + /// rate r_i is worth 1/r_now euro today instead of 1/r_i. Rates are dollars for one euro. + /// + public static decimal FxEffect(IEnumerable<(decimal AmountUsd, decimal Rate)> flows, decimal rateNow) + { + ArgumentNullException.ThrowIfNull(flows); + return rateNow <= 0m ? 0m : flows.Where(f => f.Rate > 0m).Sum(f => f.AmountUsd * (1m / rateNow - 1m / f.Rate)); + } +} + +/// +/// Photographs of the bot's equity (SPEC 7.5): every 5 minutes and at every execution, for each strategy ledger, +/// each account and each world's total in euro. Always the sum of the ledgers, never the account's balance. +/// +public sealed class EquityBook(Database db, IClock clock, Ledger ledger, FxStore fx) +{ + private sealed record Shot(string Scope, string World, Guid? AccountId, string? Strategy, string Currency, decimal Equity, decimal Cash, decimal Invested, decimal Flows, + decimal? FxEffect); + + public async Task TakeAsync(CancellationToken cancellationToken) + { + var now = clock.UtcNow; + var equities = await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false); + var accounts = (await db.ReadAsync(s => s.QueryAsync("SELECT id, environment, base_currency FROM accounts", + r => (Id: r.Id("id"), World: TradingEnvironments.World(r.Text("environment")), Currency: r.Text("base_currency"))), cancellationToken).ConfigureAwait(false)) + .ToDictionary(a => a.Id); + var shots = new List(); + foreach (var e in equities) + { + if (accounts.TryGetValue(e.AccountId, out var account)) + { + shots.Add(new Shot("strategy", account.World, e.AccountId, e.Strategy, e.Currency, e.Equity, e.Cash, e.Invested, e.Flows, null)); + } + } + + foreach (var group in shots.GroupBy(s => s.AccountId)) + { + var first = group.First(); + shots.Add(new Shot("account", first.World, first.AccountId, null, first.Currency, group.Sum(s => s.Equity), group.Sum(s => s.Cash), group.Sum(s => s.Invested), + group.Sum(s => s.Flows), null)); + } + + var rate = await UsdRateAsync(DateOnly.FromDateTime(now.UtcDateTime), cancellationToken).ConfigureAwait(false); + var flowRows = await db.ReadAsync(s => s.QueryAsync("SELECT account_id, kind, amount, currency, created_at FROM cash_ledger WHERE strategy IS NOT NULL", + r => (Account: r.Id("account_id"), Kind: r.Text("kind"), Amount: r.Money("amount"), Currency: r.Text("currency"), At: r.Moment("created_at"))), cancellationToken) + .ConfigureAwait(false); + foreach (var world in shots.Where(s => s.Scope == "account").GroupBy(s => s.World)) + { + var usd = world.Where(s => s.Currency == "USD").ToList(); + if (usd.Count > 0 && rate is null) + { + // Without a rate the euro total would be wrong: it waits for the next photograph. + continue; + } + + var usdFlows = new List<(decimal AmountUsd, decimal Rate)>(); + foreach (var row in flowRows.Where(f => LedgerKinds.IsFlow(f.Kind) && f.Currency == "USD" && usd.Any(u => u.AccountId == f.Account))) + { + usdFlows.Add((row.Amount, await UsdRateAsync(DateOnly.FromDateTime(row.At.UtcDateTime), cancellationToken).ConfigureAwait(false) ?? rate!.Value)); + } + + decimal ToEur(Shot s, decimal value) => s.Currency == "USD" ? value / rate!.Value : value; + var eurFlows = world.Where(s => s.Currency != "USD").Sum(s => s.Flows) + usdFlows.Sum(f => f.AmountUsd / f.Rate); + shots.Add(new Shot("total", world.Key, null, null, "EUR", + DbValues.Money(world.Sum(s => ToEur(s, s.Equity))), DbValues.Money(world.Sum(s => ToEur(s, s.Cash))), DbValues.Money(world.Sum(s => ToEur(s, s.Invested))), + DbValues.Money(eurFlows), usd.Count > 0 ? DbValues.Money(Returns.FxEffect(usdFlows, rate!.Value)) : null)); + } + + await db.WriteAsync(async s => + { + foreach (var shot in shots) + { + var previous = await PreviousAsync(s, shot).ConfigureAwait(false); + var index = previous?.Index is { } i && previous.Value.Flows is { } f ? i * Returns.Step(previous.Value.Equity, shot.Equity, shot.Flows - f) : 1m; + index = DbValues.Money(index); + var peak = Math.Max(previous?.Peak ?? index, index); + var drawdown = peak <= 0m ? 0m : Math.Round((index / peak - 1m) * 100m, 4, MidpointRounding.AwayFromZero); + await s.ExecuteAsync( + "INSERT INTO equity_snapshots (id, taken_at, scope, account_id, strategy, equity, cash, invested, drawdown_pct, created_at, world, currency, flows, twr_index, peak_index, fx_effect) " + + "VALUES (@id, @now, @sc, @a, @st, @e, @c, @i, @d, @now, @w, @cur, @f, @x, @p, @fx)", cancellationToken, + ("id", Ids.NewId(clock)), ("now", now), ("sc", shot.Scope), ("a", shot.AccountId), ("st", shot.Strategy), ("e", shot.Equity), ("c", shot.Cash), ("i", shot.Invested), + ("d", drawdown), ("w", shot.World), ("cur", shot.Currency), ("f", shot.Flows), ("x", index), ("p", peak), ("fx", shot.FxEffect)).ConfigureAwait(false); + } + }, cancellationToken).ConfigureAwait(false); + return shots.Count; + } + + private static async Task<(decimal Equity, decimal? Flows, decimal? Index, decimal? Peak)?> PreviousAsync(DbSession s, Shot shot) + { + var sql = "SELECT equity, flows, twr_index, peak_index FROM equity_snapshots WHERE scope = @sc AND world = @w"; + var args = new List<(string, object?)> { ("sc", shot.Scope), ("w", shot.World) }; + sql += shot.AccountId is null ? " AND account_id IS NULL" : " AND account_id = @a"; + sql += shot.Strategy is null ? " AND strategy IS NULL" : " AND strategy = @st"; + if (shot.AccountId is { } account) + { + args.Add(("a", account)); + } + + if (shot.Strategy is { } strategy) + { + args.Add(("st", strategy)); + } + + var rows = await s.QueryAsync(sql + " ORDER BY taken_at DESC, id DESC LIMIT 1", + r => (r.Money("equity"), r.MoneyOrNull("flows"), r.MoneyOrNull("twr_index"), r.MoneyOrNull("peak_index")), [.. args]).ConfigureAwait(false); + return rows.Count == 0 ? null : rows[0]; + } + + private async Task UsdRateAsync(DateOnly day, CancellationToken cancellationToken) => + (await fx.RateOnAsync("EUR", "USD", day, cancellationToken).ConfigureAwait(false) ?? await fx.LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false))?.Rate; +} diff --git a/src/Anubis/Trading/Ledger.cs b/src/Anubis/Trading/Ledger.cs new file mode 100644 index 0000000..caa22be --- /dev/null +++ b/src/Anubis/Trading/Ledger.cs @@ -0,0 +1,558 @@ +using System.Globalization; +using Anubis.Core; +using Anubis.Db; + +namespace Anubis.Trading; + +/// Kinds of row in cash_ledger (SPEC 7.5). +public static class LedgerKinds +{ + /// Entrusted capital given to or taken from a strategy: a deposit or withdrawal for the return. + public const string Capital = "capital"; + + public const string Buy = "buy"; + public const string Sell = "sell"; + public const string Fee = "fee"; + public const string Dividend = "dividend"; + + /// A residue written off the ledger at market value, as a cost of the trade (SPEC 7.2). + public const string Residue = "residue"; + + /// The counterpart of a quantity aligned to the account by the user's choice (SPEC 7.4): a flow, not a result. + public const string Adjustment = "adjustment"; + + public const string Reversal = "reversal"; + + /// Rows that move money in or out of the bot's ledgers: the return ignores them (time-weighted). + public static bool IsFlow(string kind) => kind is Capital or Adjustment; +} + +/// Order in which a sale consumes lots for the tax report (SPEC 7.5): LIFO by default, configurable. +public enum LotMethod +{ + Lifo, + Fifo, +} + +/// An execution to record, already attributed to a strategy. +public sealed record LedgerFill( + Guid AccountId, + Guid InstrumentId, + string Strategy, + string ExecutionId, + OrderSide Side, + decimal Quantity, + decimal Price, + decimal Fee, + string FeeCurrency, + DateTimeOffset ExecutedAt) +{ + public Guid? OrderId { get; init; } + + /// The reference price of the order (mid when the first step left): the slippage is measured against it. + public decimal? ReferencePrice { get; init; } + + /// Why the position is reduced, written on the trade when it closes (stop, exit, residue…). + public string? ExitReason { get; init; } +} + +/// What recording a fill changed. is false for an execution already in the ledger. +public sealed record FillOutcome(bool Recorded, decimal Quantity, decimal AveragePrice, Guid? TradeId, bool TradeClosed, decimal? SlippageBp) +{ + public Guid? FillId { get; init; } +} + +/// A position of the bot: what one strategy holds of one instrument in one account. +public sealed record LedgerPosition(Guid AccountId, Guid InstrumentId, string Strategy, decimal Quantity, decimal AveragePrice, decimal? LastPrice, decimal? StopPrice, DateTimeOffset OpenedAt) +{ + public decimal Value => Quantity * (LastPrice ?? AveragePrice); + + public decimal Unrealized => Quantity * ((LastPrice ?? AveragePrice) - AveragePrice); +} + +/// The equity of one strategy's ledger in one account, in the account's currency. +public sealed record LedgerEquity(Guid AccountId, string Strategy, string Currency, decimal Cash, decimal Invested, decimal Flows) +{ + public decimal Equity => Cash + Invested; + + /// What the strategy produced: equity minus the capital it was given. + public decimal Result => Equity - Flows; +} + +/// The ledger refuses something that would break its invariants (a sale of more than is held). +public sealed class LedgerException : Exception +{ + public LedgerException() + { + } + + public LedgerException(string message) + : base(message) + { + } + + public LedgerException(string message, Exception inner) + : base(message, inner) + { + } +} + +/// +/// The bot's books (SPEC 7.1, 7.5): one ledger for each strategy in each account, so for each strategy and +/// environment. Fills, lots and cash rows are only ever added; positions and trades are derived from them and kept +/// next to them for reading. The bot's equity is the sum of these ledgers, never the account's balance. +/// +public sealed class Ledger(Database db, IClock clock) +{ + /// Quantities below this are zero: decimal arithmetic on 18 decimals leaves nothing larger. + public const decimal Dust = 0.000000000001m; + + public LotMethod LotMethod { get; init; } = LotMethod.Lifo; + + /// Gives (positive) or takes back (negative) capital to a strategy. It counts as a flow, not a result. + public Task RecordCapitalAsync(Guid accountId, string strategy, decimal amount, string currency, string note, CancellationToken cancellationToken) => + db.WriteAsync(s => AddCashAsync(s, accountId, strategy, currency, amount, LedgerKinds.Capital, null, note, clock.UtcNow, cancellationToken), cancellationToken); + + /// + /// A correction of a strategy's cash chosen by the user after a reconciliation (SPEC 7.4): a flow, so it changes + /// the equity but not the result. + /// + public Task AdjustCashAsync(Guid accountId, string strategy, decimal amount, string currency, string note, CancellationToken cancellationToken) => + db.WriteAsync(s => AddCashAsync(s, accountId, strategy, currency, amount, LedgerKinds.Adjustment, null, note, clock.UtcNow, cancellationToken), cancellationToken); + + /// + /// Records an execution once (the account and the broker's execution id are unique) and updates position, lots + /// and trade in the same transaction. A fee taken in the bought coin reduces the quantity received. + /// + public Task RecordFillAsync(LedgerFill fill, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(fill); + if (fill.Quantity <= 0m || fill.Price < 0m || fill.Fee < 0m) + { + throw new ArgumentException("A fill has a positive quantity, a price and a non-negative fee.", nameof(fill)); + } + + return db.WriteAsync(s => RecordFillAsync(s, fill, cancellationToken), cancellationToken); + } + + internal async Task RecordFillAsync(DbSession s, LedgerFill fill, CancellationToken cancellationToken) + { + var now = clock.UtcNow; + var known = await s.FirstOrDefaultAsync("SELECT id FROM fills WHERE account_id = @a AND execution_id = @e", r => r.Id("id"), + ("a", fill.AccountId), ("e", fill.ExecutionId)).ConfigureAwait(false); + var position = await PositionAsync(s, fill.AccountId, fill.InstrumentId, fill.Strategy).ConfigureAwait(false); + if (known != Guid.Empty) + { + return new FillOutcome(false, position?.Quantity ?? 0m, position?.AveragePrice ?? 0m, null, false, null); + } + + var (baseCurrency, quoteCurrency) = await CurrenciesAsync(s, fill.InstrumentId).ConfigureAwait(false); + var feeInKind = baseCurrency is not null && fill.FeeCurrency == baseCurrency; + var quoteFee = fill.FeeCurrency == quoteCurrency ? fill.Fee : 0m; + var gross = DbValues.Money(fill.Quantity * fill.Price); + var held = position?.Quantity ?? 0m; + var average = position?.AveragePrice ?? 0m; + + // Quantity that enters or leaves the position: a fee in kind is coin that never arrives (or also leaves). + var moved = fill.Side == OrderSide.Buy + ? fill.Quantity - (feeInKind ? fill.Fee : 0m) + : fill.Quantity + (feeInKind ? fill.Fee : 0m); + if (moved <= 0m) + { + throw new LedgerException($"Execution {fill.ExecutionId}: the fee in kind takes the whole quantity."); + } + + if (fill.Side == OrderSide.Sell && moved > held + Dust) + { + throw new LedgerException( + $"Execution {fill.ExecutionId}: sells {moved.ToString(CultureInfo.InvariantCulture)} but the ledger of {fill.Strategy} holds {held.ToString(CultureInfo.InvariantCulture)}."); + } + + decimal? slippage = fill.ReferencePrice is > 0m + ? DbValues.Money((fill.Side == OrderSide.Buy ? fill.Price - fill.ReferencePrice.Value : fill.ReferencePrice.Value - fill.Price) / fill.ReferencePrice.Value * 10_000m) + : null; + var fillId = Ids.NewId(clock); + await s.ExecuteAsync( + "INSERT INTO fills (id, account_id, order_id, instrument_id, execution_id, side, quantity, price, fee, fee_currency, executed_at, created_at, strategy, reference_price, slippage_bp) " + + "VALUES (@id, @a, @o, @i, @e, @side, @q, @p, @fee, @fc, @at, @now, @st, @ref, @slip)", cancellationToken, + ("id", fillId), ("a", fill.AccountId), ("o", fill.OrderId), ("i", fill.InstrumentId), ("e", fill.ExecutionId), ("side", Wire.Text(fill.Side)), + ("q", fill.Quantity), ("p", fill.Price), ("fee", fill.Fee), ("fc", fill.FeeCurrency), ("at", fill.ExecutedAt), ("now", now), + ("st", fill.Strategy), ("ref", fill.ReferencePrice), ("slip", slippage)).ConfigureAwait(false); + + var trade = await OpenTradeAsync(s, fill.AccountId, fill.InstrumentId, fill.Strategy).ConfigureAwait(false); + var feeValue = feeInKind ? DbValues.Money(fill.Fee * fill.Price) : quoteFee; + decimal quantity; + decimal realized = 0m; + if (fill.Side == OrderSide.Buy) + { + await AddCashAsync(s, fill.AccountId, fill.Strategy, quoteCurrency, -gross, LedgerKinds.Buy, fillId, null, fill.ExecutedAt, cancellationToken).ConfigureAwait(false); + var cost = gross + quoteFee; + quantity = held + moved; + average = DbValues.Money(((held * average) + cost) / quantity); + await s.ExecuteAsync("INSERT INTO lots (id, account_id, instrument_id, fill_id, strategy, quantity, price, created_at) VALUES (@id, @a, @i, @f, @s, @q, @p, @now)", + cancellationToken, ("id", Ids.NewId(clock)), ("a", fill.AccountId), ("i", fill.InstrumentId), ("f", fillId), ("s", fill.Strategy), + ("q", moved), ("p", DbValues.Money(cost / moved)), ("now", now)).ConfigureAwait(false); + trade ??= await StartTradeAsync(s, fill, cancellationToken).ConfigureAwait(false); + await AddToTradeAsync(s, trade.Value, moved, cost, 0m, 0m, feeValue, 0m, cancellationToken).ConfigureAwait(false); + } + else + { + await AddCashAsync(s, fill.AccountId, fill.Strategy, quoteCurrency, gross, LedgerKinds.Sell, fillId, null, fill.ExecutedAt, cancellationToken).ConfigureAwait(false); + quantity = held - moved; + if (quantity < Dust) + { + quantity = 0m; + } + + realized = DbValues.Money(gross - quoteFee - (moved * average)); + await ConsumeLotsAsync(s, fill.AccountId, fill.InstrumentId, fill.Strategy, fillId, moved, fill.Price, now, cancellationToken).ConfigureAwait(false); + trade ??= await StartTradeAsync(s, fill, cancellationToken).ConfigureAwait(false); + await AddToTradeAsync(s, trade.Value, 0m, 0m, moved, gross - quoteFee, feeValue, realized, cancellationToken).ConfigureAwait(false); + } + + if (quoteFee > 0m) + { + await AddCashAsync(s, fill.AccountId, fill.Strategy, quoteCurrency, -quoteFee, LedgerKinds.Fee, fillId, null, fill.ExecutedAt, cancellationToken).ConfigureAwait(false); + } + else if (!feeInKind && fill.Fee > 0m) + { + // A fee in a third currency: kept in its own currency, so nothing is lost; it is valued at zero. + await AddCashAsync(s, fill.AccountId, fill.Strategy, fill.FeeCurrency, -fill.Fee, LedgerKinds.Fee, fillId, null, fill.ExecutedAt, cancellationToken).ConfigureAwait(false); + } + + await SavePositionAsync(s, fill.AccountId, fill.InstrumentId, fill.Strategy, quantity, average, fill.Price, position?.OpenedAt ?? fill.ExecutedAt, cancellationToken).ConfigureAwait(false); + var closed = quantity == 0m; + if (closed) + { + await s.ExecuteAsync("UPDATE trades SET status = 'closed', closed_at = @at, exit_reason = @r, updated_at = @now WHERE id = @id", cancellationToken, + ("at", fill.ExecutedAt), ("r", fill.ExitReason ?? "exit"), ("now", now), ("id", trade)).ConfigureAwait(false); + } + + return new FillOutcome(true, quantity, quantity == 0m ? 0m : average, trade, closed, slippage) { FillId = fillId }; + } + + /// A cash dividend for a strategy, recorded on the ex-date (SPEC 7.5). + public Task RecordDividendAsync(Guid accountId, string strategy, decimal amount, string currency, DateTimeOffset exDate, string note, CancellationToken cancellationToken) => + db.WriteAsync(s => AddCashAsync(s, accountId, strategy, currency, amount, LedgerKinds.Dividend, null, note, exDate, cancellationToken), cancellationToken); + + /// + /// Writes a residue off the ledger at market value (SPEC 7.2): a sale at that price that brings no money, whose + /// value becomes a cost of the trade. The position goes to zero, the trade closes, the residue is listed apart. + /// + public Task WriteOffResidueAsync(Guid accountId, Guid instrumentId, string strategy, decimal price, string reason, CancellationToken cancellationToken) => + db.WriteAsync(async s => + { + var position = await PositionAsync(s, accountId, instrumentId, strategy).ConfigureAwait(false); + if (position is null || position.Quantity <= 0m) + { + return; + } + + var (_, quote) = await CurrenciesAsync(s, instrumentId).ConfigureAwait(false); + var outcome = await RecordFillAsync(s, new LedgerFill(accountId, instrumentId, strategy, "ANURESIDUE" + Ids.NewId(clock).ToString("N"), OrderSide.Sell, + position.Quantity, price, 0m, quote, clock.UtcNow) + { ExitReason = "residue" }, cancellationToken).ConfigureAwait(false); + var value = DbValues.Money(position.Quantity * price); + await AddCashAsync(s, accountId, strategy, quote, -value, LedgerKinds.Residue, outcome.FillId, reason, clock.UtcNow, cancellationToken).ConfigureAwait(false); + if (outcome.TradeId is { } trade) + { + await AddToTradeAsync(s, trade, 0m, 0m, 0m, 0m, value, -value, cancellationToken).ConfigureAwait(false); + } + + await s.ExecuteAsync("INSERT INTO residues (id, account_id, instrument_id, strategy, quantity, value, currency, reason, created_at) VALUES (@id, @a, @i, @s, @q, @v, @c, @r, @now)", + cancellationToken, ("id", Ids.NewId(clock)), ("a", accountId), ("i", instrumentId), ("s", strategy), ("q", position.Quantity), ("v", value), + ("c", quote), ("r", reason), ("now", clock.UtcNow)).ConfigureAwait(false); + }, cancellationToken); + + /// + /// Aligns the ledger to the account by the user's choice (SPEC 7.4): a quantity enters or leaves at market price, + /// with an adjustment row that makes it a flow, so it does not look like a gain or a loss. + /// + public Task AdjustQuantityAsync(Guid accountId, Guid instrumentId, string strategy, decimal delta, decimal price, string note, CancellationToken cancellationToken) => + db.WriteAsync(async s => + { + if (delta == 0m) + { + return; + } + + var (_, quote) = await CurrenciesAsync(s, instrumentId).ConfigureAwait(false); + var side = delta > 0m ? OrderSide.Buy : OrderSide.Sell; + await RecordFillAsync(s, new LedgerFill(accountId, instrumentId, strategy, "ANUADJUST" + Ids.NewId(clock).ToString("N"), side, + Math.Abs(delta), price, 0m, quote, clock.UtcNow) + { ExitReason = "adjustment" }, cancellationToken).ConfigureAwait(false); + var value = DbValues.Money(delta * price); + await AddCashAsync(s, accountId, strategy, quote, value, LedgerKinds.Adjustment, null, note, clock.UtcNow, cancellationToken).ConfigureAwait(false); + }, cancellationToken); + + /// + /// A split in an account's ledger (SPEC 6.10): quantities times the ratio, average prices, stops and open lots + /// divided by it; values and results do not change. False when the action was already applied. + /// + public Task ApplySplitAsync(Guid accountId, Guid instrumentId, string sourceKey, decimal ratio, CancellationToken cancellationToken) + { + ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(ratio, 0m); + return db.WriteAsync(async s => + { + if (await s.CountAsync("SELECT COUNT(*) FROM applied_actions WHERE account_id = @a AND source_key = @k", ("a", accountId), ("k", sourceKey)).ConfigureAwait(false) > 0) + { + return false; + } + + var now = clock.UtcNow; + var positions = (await s.QueryAsync("SELECT account_id, instrument_id, strategy, quantity, average_price, last_price, stop_price, opened_at FROM positions WHERE account_id = @a AND instrument_id = @i", + ReadPosition, ("a", accountId), ("i", instrumentId)).ConfigureAwait(false)).ToList(); + foreach (var p in positions) + { + await s.ExecuteAsync("UPDATE positions SET quantity = @q, average_price = @p, last_price = @l, stop_price = @st, updated_at = @now WHERE account_id = @a AND instrument_id = @i AND strategy = @s", + cancellationToken, ("q", p.Quantity * ratio), ("p", DbValues.Money(p.AveragePrice / ratio)), ("l", p.LastPrice / ratio), ("st", p.StopPrice / ratio), ("now", now), + ("a", accountId), ("i", instrumentId), ("s", p.Strategy)).ConfigureAwait(false); + var lots = await s.QueryAsync("SELECT id, fill_id, quantity, price, closes_id FROM lots WHERE account_id = @a AND instrument_id = @i AND strategy = @s", + r => (Id: r.Id("id"), Fill: r.Id("fill_id"), Quantity: r.Money("quantity"), Price: r.Money("price"), Closes: r.IdOrNull("closes_id")), + ("a", accountId), ("i", instrumentId), ("s", p.Strategy)).ConfigureAwait(false); + foreach (var lot in lots.Where(l => l.Closes is null && l.Quantity > 0m)) + { + var remaining = lot.Quantity + lots.Where(c => c.Closes == lot.Id).Sum(c => c.Quantity); + if (remaining <= Dust) + { + continue; + } + + await s.ExecuteAsync("INSERT INTO lots (id, account_id, instrument_id, fill_id, strategy, quantity, price, created_at, closes_id) VALUES (@id, @a, @i, @f, @s, @q, @p, @now, @c)", + cancellationToken, ("id", Ids.NewId(clock)), ("a", accountId), ("i", instrumentId), ("f", lot.Fill), ("s", p.Strategy), ("q", -remaining), ("p", lot.Price), + ("now", now), ("c", lot.Id)).ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO lots (id, account_id, instrument_id, fill_id, strategy, quantity, price, created_at) VALUES (@id, @a, @i, @f, @s, @q, @p, @now)", + cancellationToken, ("id", Ids.NewId(clock)), ("a", accountId), ("i", instrumentId), ("f", lot.Fill), ("s", p.Strategy), ("q", remaining * ratio), + ("p", DbValues.Money(lot.Price / ratio)), ("now", now)).ConfigureAwait(false); + } + + if (await OpenTradeAsync(s, accountId, instrumentId, p.Strategy).ConfigureAwait(false) is { } trade) + { + var row = await s.FirstOrDefaultAsync("SELECT bought_quantity, sold_quantity FROM trades WHERE id = @id", r => (B: r.Money("bought_quantity"), S: r.Money("sold_quantity")), ("id", trade)) + .ConfigureAwait(false); + await s.ExecuteAsync("UPDATE trades SET bought_quantity = @b, sold_quantity = @s, updated_at = @now WHERE id = @id", cancellationToken, + ("b", row.B * ratio), ("s", row.S * ratio), ("now", now), ("id", trade)).ConfigureAwait(false); + } + } + + await s.ExecuteAsync("INSERT INTO applied_actions (id, account_id, source_key, created_at) VALUES (@id, @a, @k, @now)", cancellationToken, + ("id", Ids.NewId(clock)), ("a", accountId), ("k", sourceKey), ("now", now)).ConfigureAwait(false); + return true; + }, cancellationToken); + } + + /// Cancels a cash row with an opposite one that points at it: the only way to correct the ledger. + public Task ReverseCashAsync(Guid cashId, string note, CancellationToken cancellationToken) => + db.WriteAsync(async s => + { + var row = await s.FirstOrDefaultAsync("SELECT account_id, strategy, currency, amount, kind FROM cash_ledger WHERE id = @id", + r => (Account: r.Id("account_id"), Strategy: r.TextOrNull("strategy"), Currency: r.Text("currency"), Amount: r.Money("amount"), Kind: r.Text("kind")), + ("id", cashId)).ConfigureAwait(false); + if (row.Currency is null) + { + throw new LedgerException("Unknown ledger row " + cashId); + } + + if (await s.CountAsync("SELECT COUNT(*) FROM cash_ledger WHERE reverses_id = @id", ("id", cashId)).ConfigureAwait(false) > 0) + { + return; + } + + await s.ExecuteAsync( + "INSERT INTO cash_ledger (id, account_id, currency, amount, kind, reverses_id, note, occurred_at, created_at, strategy) VALUES (@id, @a, @c, @m, @k, @r, @n, @at, @at, @s)", + cancellationToken, ("id", Ids.NewId(clock)), ("a", row.Account), ("c", row.Currency), ("m", -row.Amount), + ("k", LedgerKinds.IsFlow(row.Kind) ? row.Kind : LedgerKinds.Reversal), ("r", cashId), ("n", note), ("at", clock.UtcNow), ("s", row.Strategy)).ConfigureAwait(false); + }, cancellationToken); + + /// Writes the latest price of an instrument on the positions that hold it, for their value. + public Task MarkAsync(Guid instrumentId, decimal price, CancellationToken cancellationToken) => + db.WriteAsync(s => s.ExecuteAsync("UPDATE positions SET last_price = @p, updated_at = @now WHERE instrument_id = @i", cancellationToken, + ("p", price), ("now", clock.UtcNow), ("i", instrumentId)), cancellationToken); + + /// Sets the protective level shown with a position. + public Task SetStopAsync(Guid accountId, Guid instrumentId, string strategy, decimal? stop, CancellationToken cancellationToken) => + db.WriteAsync(s => s.ExecuteAsync("UPDATE positions SET stop_price = @p, updated_at = @now WHERE account_id = @a AND instrument_id = @i AND strategy = @s", cancellationToken, + ("p", stop), ("now", clock.UtcNow), ("a", accountId), ("i", instrumentId), ("s", strategy)), cancellationToken); + + public Task> PositionsAsync(Guid? accountId, CancellationToken cancellationToken) => + db.ReadAsync>(async s => (await s.QueryAsync( + "SELECT account_id, instrument_id, strategy, quantity, average_price, last_price, stop_price, opened_at FROM positions" + + (accountId is null ? "" : " WHERE account_id = @a") + " ORDER BY opened_at, id", ReadPosition, + accountId is null ? [] : [("a", accountId)]).ConfigureAwait(false)).Where(p => p.Quantity > 0m).ToList(), cancellationToken); + + public Task PositionAsync(Guid accountId, Guid instrumentId, string strategy, CancellationToken cancellationToken) => + db.ReadAsync(s => PositionAsync(s, accountId, instrumentId, strategy), cancellationToken); + + /// + /// The equity of every ledger: cash in the account's currency plus positions at their last price. Rows in other + /// currencies (a fee in a third coin) are kept but not valued. + /// + public Task> EquitiesAsync(CancellationToken cancellationToken) => + db.ReadAsync>(async s => + { + var accounts = await s.QueryAsync("SELECT id, base_currency FROM accounts", r => (Id: r.Id("id"), Currency: r.Text("base_currency"))).ConfigureAwait(false); + var cash = await s.QueryAsync("SELECT account_id, strategy, currency, kind, amount FROM cash_ledger WHERE strategy IS NOT NULL", + r => (Account: r.Id("account_id"), Strategy: r.Text("strategy"), Currency: r.Text("currency"), Kind: r.Text("kind"), Amount: r.Money("amount"))).ConfigureAwait(false); + var positions = (await s.QueryAsync("SELECT account_id, instrument_id, strategy, quantity, average_price, last_price, stop_price, opened_at FROM positions", + ReadPosition).ConfigureAwait(false)).Where(p => p.Quantity > 0m).ToList(); + var result = new List(); + foreach (var account in accounts) + { + var strategies = cash.Where(c => c.Account == account.Id).Select(c => c.Strategy) + .Concat(positions.Where(p => p.AccountId == account.Id).Select(p => p.Strategy)) + .Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal); + foreach (var strategy in strategies) + { + var rows = cash.Where(c => c.Account == account.Id && c.Strategy == strategy && c.Currency == account.Currency).ToList(); + result.Add(new LedgerEquity(account.Id, strategy, account.Currency, + rows.Sum(r => r.Amount), + positions.Where(p => p.AccountId == account.Id && p.Strategy == strategy).Sum(p => DbValues.Money(p.Value)), + rows.Where(r => LedgerKinds.IsFlow(r.Kind)).Sum(r => r.Amount))); + } + } + + return result; + }, cancellationToken); + + /// + /// What a strategy held of an instrument just before , from the fills alone: the base of a + /// dividend, which goes to whoever held the stock at the close before the ex-date (SPEC 7.5). + /// + public Task QuantityAtAsync(Guid accountId, Guid instrumentId, string strategy, DateTimeOffset at, CancellationToken cancellationToken) => + db.ReadAsync(async s => + { + var (baseCurrency, _) = await CurrenciesAsync(s, instrumentId).ConfigureAwait(false); + var rows = await s.QueryAsync("SELECT side, quantity, fee, fee_currency FROM fills WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND executed_at < @at", + r => (Side: Wire.Side(r.Text("side")), Quantity: r.Money("quantity"), Fee: r.Money("fee"), FeeCurrency: r.Text("fee_currency")), + ("a", accountId), ("i", instrumentId), ("s", strategy), ("at", at)).ConfigureAwait(false); + return rows.Sum(r => + { + var inKind = baseCurrency is not null && r.FeeCurrency == baseCurrency ? r.Fee : 0m; + return r.Side == OrderSide.Buy ? r.Quantity - inKind : -(r.Quantity + inKind); + }); + }, cancellationToken); + + /// Open lots of a position with what is left of each, in the order of the tax method. + public Task> OpenLotsAsync(Guid accountId, Guid instrumentId, string strategy, CancellationToken cancellationToken) => + db.ReadAsync(s => OpenLotsAsync(s, accountId, instrumentId, strategy), cancellationToken); + + private async Task> OpenLotsAsync(DbSession s, Guid accountId, Guid instrumentId, string strategy) + { + var rows = await s.QueryAsync("SELECT id, quantity, price, closes_id, created_at FROM lots WHERE account_id = @a AND instrument_id = @i AND strategy = @s ORDER BY created_at, id", + r => (Id: r.Id("id"), Quantity: r.Money("quantity"), Price: r.Money("price"), Closes: r.IdOrNull("closes_id")), + ("a", accountId), ("i", instrumentId), ("s", strategy)).ConfigureAwait(false); + var open = rows.Where(r => r.Closes is null && r.Quantity > 0m) + .Select(r => (Lot: r.Id, Remaining: r.Quantity + rows.Where(c => c.Closes == r.Id).Sum(c => c.Quantity), r.Price)) + .Where(l => l.Remaining > Dust) + .ToList(); + if (LotMethod == LotMethod.Lifo) + { + open.Reverse(); + } + + return open; + } + + private async Task ConsumeLotsAsync(DbSession s, Guid accountId, Guid instrumentId, string strategy, Guid fillId, decimal quantity, decimal price, DateTimeOffset now, CancellationToken cancellationToken) + { + var left = quantity; + foreach (var (lot, remaining, _) in await OpenLotsAsync(s, accountId, instrumentId, strategy).ConfigureAwait(false)) + { + if (left <= Dust) + { + break; + } + + var take = Math.Min(left, remaining); + await s.ExecuteAsync("INSERT INTO lots (id, account_id, instrument_id, fill_id, strategy, quantity, price, created_at, closes_id) VALUES (@id, @a, @i, @f, @s, @q, @p, @now, @c)", + cancellationToken, ("id", Ids.NewId(clock)), ("a", accountId), ("i", instrumentId), ("f", fillId), ("s", strategy), ("q", -take), ("p", price), + ("now", now), ("c", lot)).ConfigureAwait(false); + left -= take; + } + } + + private async Task AddCashAsync(DbSession s, Guid accountId, string strategy, string currency, decimal amount, string kind, Guid? fillId, string? note, DateTimeOffset at, CancellationToken cancellationToken) + { + if (amount == 0m) + { + return; + } + + await s.ExecuteAsync( + "INSERT INTO cash_ledger (id, account_id, currency, amount, kind, fill_id, note, occurred_at, created_at, strategy) VALUES (@id, @a, @c, @m, @k, @f, @n, @at, @now, @s)", + cancellationToken, ("id", Ids.NewId(clock)), ("a", accountId), ("c", currency), ("m", amount), ("k", kind), ("f", fillId), ("n", note), + ("at", at), ("now", clock.UtcNow), ("s", strategy)).ConfigureAwait(false); + } + + private async Task SavePositionAsync(DbSession s, Guid accountId, Guid instrumentId, string strategy, decimal quantity, decimal average, decimal lastPrice, DateTimeOffset openedAt, CancellationToken cancellationToken) + { + var now = clock.UtcNow; + if (quantity == 0m) + { + await s.ExecuteAsync("DELETE FROM positions WHERE account_id = @a AND instrument_id = @i AND strategy = @s", cancellationToken, + ("a", accountId), ("i", instrumentId), ("s", strategy)).ConfigureAwait(false); + return; + } + + var changed = await s.ExecuteAsync("UPDATE positions SET quantity = @q, average_price = @p, last_price = @l, updated_at = @now WHERE account_id = @a AND instrument_id = @i AND strategy = @s", + cancellationToken, ("q", quantity), ("p", average), ("l", lastPrice), ("now", now), ("a", accountId), ("i", instrumentId), ("s", strategy)).ConfigureAwait(false); + if (changed == 0) + { + await s.ExecuteAsync( + "INSERT INTO positions (id, account_id, instrument_id, strategy, quantity, average_price, last_price, opened_at, created_at, updated_at) VALUES (@id, @a, @i, @s, @q, @p, @l, @o, @now, @now)", + cancellationToken, ("id", Ids.NewId(clock)), ("a", accountId), ("i", instrumentId), ("s", strategy), ("q", quantity), ("p", average), ("l", lastPrice), + ("o", openedAt), ("now", now)).ConfigureAwait(false); + } + } + + private async Task StartTradeAsync(DbSession s, LedgerFill fill, CancellationToken cancellationToken) + { + var id = Ids.NewId(clock); + await s.ExecuteAsync( + "INSERT INTO trades (id, account_id, instrument_id, strategy, status, opened_at, bought_quantity, bought_value, sold_quantity, sold_value, fees, realized, created_at, updated_at) " + + "VALUES (@id, @a, @i, @s, 'open', @at, 0, 0, 0, 0, 0, 0, @now, @now)", + cancellationToken, ("id", id), ("a", fill.AccountId), ("i", fill.InstrumentId), ("s", fill.Strategy), ("at", fill.ExecutedAt), ("now", clock.UtcNow)).ConfigureAwait(false); + return id; + } + + // Money is never summed in SQL: on SQLite it is text and the engine would go through floating point (trap 19). + private async Task AddToTradeAsync(DbSession s, Guid trade, decimal bought, decimal boughtValue, decimal sold, decimal soldValue, decimal fees, decimal realized, CancellationToken cancellationToken) + { + var row = await s.FirstOrDefaultAsync("SELECT bought_quantity, bought_value, sold_quantity, sold_value, fees, realized FROM trades WHERE id = @id", + r => (Bq: r.Money("bought_quantity"), Bv: r.Money("bought_value"), Sq: r.Money("sold_quantity"), Sv: r.Money("sold_value"), F: r.Money("fees"), R: r.Money("realized")), + ("id", trade)).ConfigureAwait(false); + await s.ExecuteAsync( + "UPDATE trades SET bought_quantity = @bq, bought_value = @bv, sold_quantity = @sq, sold_value = @sv, fees = @f, realized = @r, updated_at = @now WHERE id = @id", + cancellationToken, ("bq", row.Bq + bought), ("bv", row.Bv + boughtValue), ("sq", row.Sq + sold), ("sv", row.Sv + soldValue), ("f", row.F + fees), + ("r", row.R + realized), ("now", clock.UtcNow), ("id", trade)).ConfigureAwait(false); + } + + private static async Task OpenTradeAsync(DbSession s, Guid accountId, Guid instrumentId, string strategy) + { + var id = await s.FirstOrDefaultAsync("SELECT id FROM trades WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND status = 'open'", + r => r.Id("id"), ("a", accountId), ("i", instrumentId), ("s", strategy)).ConfigureAwait(false); + return id == Guid.Empty ? null : id; + } + + private static Task PositionAsync(DbSession s, Guid accountId, Guid instrumentId, string strategy) => + s.FirstOrDefaultAsync("SELECT account_id, instrument_id, strategy, quantity, average_price, last_price, stop_price, opened_at FROM positions WHERE account_id = @a AND instrument_id = @i AND strategy = @s", + ReadPosition, ("a", accountId), ("i", instrumentId), ("s", strategy)); + + private static async Task<(string? Base, string Quote)> CurrenciesAsync(DbSession s, Guid instrumentId) + { + var row = await s.FirstOrDefaultAsync("SELECT symbol, base_currency, quote_currency FROM instruments WHERE id = @i", + r => (Symbol: r.Text("symbol"), Base: r.TextOrNull("base_currency"), Quote: r.Text("quote_currency")), ("i", instrumentId)).ConfigureAwait(false); + if (row.Quote is null) + { + throw new LedgerException("Unknown instrument " + instrumentId); + } + + // OKX symbols are BASE-QUOTE; older rows may lack the base column. + var baseCurrency = row.Base ?? (row.Symbol.Contains('-', StringComparison.Ordinal) ? row.Symbol.Split('-')[0] : null); + return (baseCurrency, row.Quote); + } + + private static LedgerPosition ReadPosition(DbRow r) => new( + r.Id("account_id"), r.Id("instrument_id"), r.Text("strategy"), r.Money("quantity"), r.Money("average_price"), + r.MoneyOrNull("last_price"), r.MoneyOrNull("stop_price"), r.Moment("opened_at")); +} diff --git a/src/Anubis/Trading/LiveGuard.cs b/src/Anubis/Trading/LiveGuard.cs new file mode 100644 index 0000000..01adea4 --- /dev/null +++ b/src/Anubis/Trading/LiveGuard.cs @@ -0,0 +1,71 @@ +using Anubis.Platform; + +namespace Anubis.Trading; + +/// +/// The startup consent for real money (SPEC 2.2, 15.1, 15.6): ANUBIS_ALLOW_LIVE=1 in Docker, +/// allow_live = true in config.toml on desktop. Only the startup configuration can give it. +/// +public sealed class TradingConsent +{ + private TradingConsent(bool allowLive, string source) + { + AllowLive = allowLive; + Source = source; + } + + public bool AllowLive { get; } + + /// Where the answer came from, for the error message. + public string Source { get; } + + /// No consent: what tests, the demo mode and every tool use. + public static TradingConsent None { get; } = new(false, "nessuna configurazione d'avvio"); + + public static TradingConsent From(StartupConfig startup) + { + ArgumentNullException.ThrowIfNull(startup); + return new(startup.AllowLive, startup.Platform == PlatformKind.Docker ? "ANUBIS_ALLOW_LIVE" : "allow_live in config.toml"); + } +} + +/// A real account was asked for without the startup consent. +public sealed class LiveTradingRefusedException : Exception +{ + public LiveTradingRefusedException() + { + } + + public LiveTradingRefusedException(string message) + : base(message) + { + } + + public LiveTradingRefusedException(string message, Exception inner) + : base(message, inner) + { + } +} + +/// +/// The guard every broker adapter runs in its constructor (SPEC 2.2): a real environment without the startup +/// consent is refused before any connection, any key read, any request. +/// +public static class LiveGuard +{ + public static void Ensure(string environment, TradingConsent consent) + { + ArgumentNullException.ThrowIfNull(consent); + if (!TradingEnvironments.IsKnown(environment)) + { + throw new ArgumentException($"Ambiente sconosciuto: '{environment}'.", nameof(environment)); + } + + if (environment == TradingEnvironments.Live && !consent.AllowLive) + { + throw new LiveTradingRefusedException( + $"Conto reale rifiutato: la configurazione d'avvio non consente i soldi veri ({consent.Source}). " + + "Si usano solo il simulatore interno e i conti di prova."); + } + } +} diff --git a/src/Anubis/Trading/OkxTrading.cs b/src/Anubis/Trading/OkxTrading.cs new file mode 100644 index 0000000..656bd27 --- /dev/null +++ b/src/Anubis/Trading/OkxTrading.cs @@ -0,0 +1,459 @@ +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Text.Json; +using Anubis.Brokers; +using Anubis.Core; +using Anubis.Data; + +namespace Anubis.Trading; + +/// Addresses of OKX Europe's trading API for an environment (SPEC 4.2, API-NOTES). +public sealed record OkxTradingOptions +{ + public required string Environment { get; init; } + + /// Production and demo share the REST host; the demo adds the x-simulated-trading: 1 header. + public Uri RestUrl { get; init; } = new("https://eea.okx.com"); + + public Uri PrivateStreamUrl => Environment == TradingEnvironments.Live ? new("wss://wseea.okx.com/ws/v5/private") : new("wss://wseeapap.okx.com/ws/v5/private"); + + public string QuoteCurrency { get; init; } = "EUR"; + + public bool Demo => Environment != TradingEnvironments.Live; +} + +/// +/// The account side of OKX Europe spot (SPEC 4.2, 5.3). Ordinary orders on /trade/order; protective stops +/// as trigger orders on /trade/order-algo, which do not lock the coins. Fills from /trade/fills with +/// the trade id as execution id. The demo account in development; a live account only with the startup consent. +/// +public sealed class OkxTrading : IBrokerAccount +{ + private readonly TradingHttp _http; + private readonly IClock _clock; + private readonly OkxCredentials _credentials; + private readonly OkxTradingOptions _options; + private readonly Func _sockets; + private readonly RateLimiter _trade; + private readonly RateLimiter _read; + + public OkxTrading(HttpClient http, IClock clock, OkxCredentials credentials, OkxTradingOptions options, TradingConsent consent, Func? sockets = null) + { + ArgumentNullException.ThrowIfNull(options); + LiveGuard.Ensure(options.Environment, consent); + if (options.Environment == TradingEnvironments.Simulation) + { + throw new ArgumentException("Il simulatore interno non passa da OKX.", nameof(options)); + } + + _http = new TradingHttp(http, clock, "OKX"); + _clock = clock; + _credentials = credentials ?? throw new ArgumentNullException(nameof(credentials)); + _options = options; + _sockets = sockets ?? (() => new ClientWebSocketTransport()); + + // Place, cancel and query: 60 every 2 s; balance and account settings are slower (API-NOTES). Kept lower. + _trade = new RateLimiter(clock, 20, TimeSpan.FromSeconds(2)); + _read = new RateLimiter(clock, 4, TimeSpan.FromSeconds(2)); + } + + public string Venue => Venues.Okx; + + public string Environment => _options.Environment; + + public BrokerCapabilities Capabilities { get; } = new() + { + Fractional = true, + PostOnly = true, + FeeInKind = true, + StopsAreTriggerOrders = true, + }; + + public async Task ServerTimeAsync(CancellationToken cancellationToken) + { + var data = await CallAsync(HttpMethod.Get, "/api/v5/public/time", null, _read, cancellationToken).ConfigureAwait(false); + return Millis(Text(data[0], "ts")!); + } + + public async Task GetAccountAsync(CancellationToken cancellationToken) + { + var balances = await BalancesAsync(cancellationToken).ConfigureAwait(false); + var cash = balances.GetValueOrDefault(_options.QuoteCurrency); + + // Coins are valued by the caller with its own prices: the account's total is in USD and not used. + return new AccountSnapshot(_options.QuoteCurrency, cash, balances, _clock.UtcNow) { BuyingPower = cash }; + } + + public async Task> GetPositionsAsync(CancellationToken cancellationToken) + { + var balances = await BalancesAsync(cancellationToken).ConfigureAwait(false); + return balances.Where(b => b.Key != _options.QuoteCurrency && b.Key is not ("USDC" or "USDT" or "EUR" or "USD") && b.Value > 0m) + .Select(b => new BrokerPosition(b.Key + "-" + _options.QuoteCurrency, b.Value, null)) + .ToList(); + } + + public async Task> GetOpenOrdersAsync(CancellationToken cancellationToken) + { + var orders = await CallAsync(HttpMethod.Get, "/api/v5/trade/orders-pending?instType=SPOT", null, _trade, cancellationToken).ConfigureAwait(false); + var algos = await CallAsync(HttpMethod.Get, "/api/v5/trade/orders-algo-pending?ordType=trigger&instType=SPOT", null, _trade, cancellationToken).ConfigureAwait(false); + return orders.Select(ReadOrder).Concat(algos.Select(ReadAlgo)).ToList(); + } + + public async Task SubmitOrderAsync(OrderRequest request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + var stop = request.Kind == OrderKind.Stop; + var (path, body) = stop ? ("/api/v5/trade/order-algo", AlgoBody(request)) : ("/api/v5/trade/order", OrderBody(request)); + var url = new Uri(_options.RestUrl, path); + var answer = await _http.SendAsync(HttpMethod.Post, url, body, b => Sign("POST", path, b), _trade, retry: false, cancellationToken).ConfigureAwait(false); + var (code, message, data) = Envelope(answer); + var item = data.FirstOrDefault(); + var sCode = item.ValueKind == JsonValueKind.Object ? Text(item, "sCode") ?? code : code; + if (code == "0" && sCode == "0") + { + return new BrokerOrder(request.ClientOrderId, Text(item, stop ? "algoId" : "ordId"), request.Symbol, request.Side, request.Kind, request.Quantity, + OrderStatus.Submitted, 0m, _clock.UtcNow) + { + LimitPrice = request.LimitPrice, + StopPrice = request.StopPrice, + TimeInForce = request.TimeInForce, + }; + } + + // 51016 / 51065: the id is already pending on OKX, so an earlier send arrived (API-NOTES). + if (sCode is "51016" or "51065") + { + return await GetOrderAsync(request.ClientOrderId, request.Symbol, cancellationToken).ConfigureAwait(false) + ?? throw new OrderRejectedException("OKX: identificativo già usato da un altro ordine.", "duplicate_client_order_id"); + } + + if (!answer.Ok && (int)answer.Status is 401 or 403) + { + throw _http.Failure(url, answer); + } + + var reason = item.ValueKind == JsonValueKind.Object ? Text(item, "sMsg") : message; + throw new OrderRejectedException($"OKX: ordine {request.ClientOrderId} rifiutato ({sCode}): {Redactor.Redact(reason ?? "")}", "okx_" + sCode); + } + + public async Task CancelOrderAsync(string clientOrderId, string symbol, CancellationToken cancellationToken) + { + var stop = IsStop(clientOrderId); + var (path, body) = stop + ? ("/api/v5/trade/cancel-algos", JsonSerializer.Serialize(new[] { new Dictionary { ["instId"] = symbol, ["algoClOrdId"] = clientOrderId } })) + : ("/api/v5/trade/cancel-order", JsonSerializer.Serialize(new Dictionary { ["instId"] = symbol, ["clOrdId"] = clientOrderId })); + var url = new Uri(_options.RestUrl, path); + var answer = await _http.SendAsync(HttpMethod.Post, url, body, b => Sign("POST", path, b), _trade, retry: true, cancellationToken).ConfigureAwait(false); + var (code, _, data) = Envelope(answer); + var sCode = data.Count > 0 ? Text(data[0], "sCode") ?? code : code; + + // 51400: already filled, canceled or unknown; 51410: already being canceled. The caller reads the order next. + if (code != "0" && sCode is not ("51400" or "51410" or "51603")) + { + throw _http.Failure(url, answer); + } + } + + public async Task GetOrderAsync(string clientOrderId, string symbol, CancellationToken cancellationToken) + { + var stop = IsStop(clientOrderId); + var path = stop + ? "/api/v5/trade/order-algo?algoClOrdId=" + Uri.EscapeDataString(clientOrderId) + : $"/api/v5/trade/order?instId={Uri.EscapeDataString(symbol)}&clOrdId={Uri.EscapeDataString(clientOrderId)}"; + var url = new Uri(_options.RestUrl, path); + var answer = await _http.SendAsync(HttpMethod.Get, url, null, b => Sign("GET", path, b), _trade, retry: true, cancellationToken).ConfigureAwait(false); + var (code, _, data) = Envelope(answer); + if (code != "0" || data.Count == 0) + { + // 51603 "Order does not exist"; a canceled order without fills also disappears after two hours. + return code is "0" or "51603" or "51000" or "1" ? null : throw _http.Failure(url, answer); + } + + return stop ? ReadAlgo(data[0]) : ReadOrder(data[0]); + } + + public async Task> GetFillsAsync(DateTimeOffset since, CancellationToken cancellationToken) + { + var fills = new List(); + string? after = null; + for (var page = 0; page < 30; page++) + { + var path = "/api/v5/trade/fills?instType=SPOT&limit=100&begin=" + since.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture) + + (after is null ? "" : "&after=" + after); + var data = await CallAsync(HttpMethod.Get, path, null, _trade, cancellationToken).ConfigureAwait(false); + foreach (var item in data) + { + var clientId = Text(item, "clOrdId"); + if (string.IsNullOrEmpty(clientId)) + { + // A triggered stop: its order carries the id of the trigger order that created it. + clientId = await AlgoClientIdAsync(Text(item, "instId")!, Text(item, "ordId")!, cancellationToken).ConfigureAwait(false); + } + + fills.Add(ReadFill(item, clientId ?? "")); + } + + if (data.Count < 100) + { + break; + } + + after = Text(data[^1], "billId"); + } + + return fills; + } + + /// Spot crypto has no dividends; deposits and withdrawals do not change the bot's capital (SPEC 7.1). + public Task> GetCashActivitiesAsync(DateTimeOffset since, CancellationToken cancellationToken) => + Task.FromResult>([]); + + /// perm of the account configuration: read_only, trade, withdraw (API-NOTES). + public async Task GetKeyPermissionsAsync(CancellationToken cancellationToken) + { + var data = await CallAsync(HttpMethod.Get, "/api/v5/account/config", null, _read, cancellationToken).ConfigureAwait(false); + return ReadPermissions(data[0]); + } + + public static KeyPermissions ReadPermissions(JsonElement config) + { + var perm = (Text(config, "perm") ?? "").Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); + var feeType = Text(config, "feeType"); + var fees = feeType == "1" ? "commissioni nella valuta di quotazione" : "commissioni nella moneta ricevuta"; + return new KeyPermissions(perm.Contains("read_only") || perm.Length > 0, perm.Contains("trade"), perm.Contains("withdraw"), + "Permessi della chiave: " + string.Join(", ", perm) + "; " + fees + "."); + } + + public async IAsyncEnumerable StreamOrderUpdatesAsync([EnumeratorCancellation] CancellationToken cancellationToken) + { + await using var socket = _sockets(); + await socket.ConnectAsync(_options.PrivateStreamUrl, null, cancellationToken).ConfigureAwait(false); + var timestamp = _clock.UtcNow.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture); + var login = new + { + op = "login", + args = new[] + { + new { apiKey = _credentials.Key, passphrase = _credentials.Passphrase, timestamp, sign = OkxSigner.Sign(timestamp, "GET", "/users/self/verify", "", _credentials.Secret) }, + }, + }; + await socket.SendAsync(JsonSerializer.Serialize(login), cancellationToken).ConfigureAwait(false); + while (await socket.ReceiveAsync(cancellationToken).ConfigureAwait(false) is { } message) + { + if (message == "pong") + { + continue; + } + + using var json = JsonDocument.Parse(message); + var root = json.RootElement; + var @event = Text(root, "event"); + if (@event == "login") + { + await socket.SendAsync("""{"op":"subscribe","args":[{"channel":"orders","instType":"SPOT"}]}""", cancellationToken).ConfigureAwait(false); + continue; + } + + if (@event == "error") + { + throw new BrokerException("OKX: flusso degli ordini rifiutato (" + Text(root, "code") + ").", retryable: false); + } + + foreach (var update in ParseOrdersPush(root)) + { + yield return update; + } + } + } + + /// The updates in one push of the orders channel; subscriptions and notices give none. + public static IReadOnlyList ParseOrdersPush(JsonElement root) + { + if (!root.TryGetProperty("data", out var data) || data.ValueKind != JsonValueKind.Array) + { + return []; + } + + var updates = new List(); + foreach (var item in data.EnumerateArray()) + { + var order = ReadOrder(item); + BrokerFill? fill = null; + if (Number(item, "fillSz") is > 0m && !string.IsNullOrEmpty(Text(item, "tradeId"))) + { + fill = new BrokerFill(Text(item, "instId") + ":" + Text(item, "tradeId"), order.ClientOrderId, order.Symbol, order.Side, + Number(item, "fillSz")!.Value, Number(item, "fillPx") ?? 0m, -(Number(item, "fillFee") ?? 0m), Text(item, "fillFeeCcy") ?? "", Millis(Text(item, "fillTime")!)); + } + + updates.Add(new OrderUpdate(order, fill)); + } + + return updates; + } + + public static BrokerOrder ReadOrder(JsonElement o) + { + var filled = Number(o, "accFillSz") ?? 0m; + var status = Text(o, "state") switch + { + "filled" => OrderStatus.Filled, + "partially_filled" => OrderStatus.PartiallyFilled, + "canceled" or "mmp_canceled" => OrderStatus.Canceled, + _ when filled > 0m => OrderStatus.PartiallyFilled, + _ => OrderStatus.Submitted, + }; + var type = Text(o, "ordType"); + return new BrokerOrder(Text(o, "clOrdId") ?? "", Text(o, "ordId"), Text(o, "instId") ?? "", Text(o, "side") == "sell" ? OrderSide.Sell : OrderSide.Buy, + type == "market" ? OrderKind.Market : OrderKind.Limit, Number(o, "sz") ?? 0m, status, filled, Millis(Text(o, "uTime") ?? Text(o, "cTime") ?? "0")) + { + LimitPrice = type == "market" ? null : Number(o, "px"), + TimeInForce = type == "ioc" ? TimeInForce.Ioc : TimeInForce.Gtc, + AverageFillPrice = Number(o, "avgPx"), + Reason = Text(o, "cancelSourceReason") is { Length: > 0 } reason ? reason : null, + }; + } + + public static BrokerOrder ReadAlgo(JsonElement o) + { + var status = Text(o, "state") switch + { + "effective" => OrderStatus.Filled, + "partially_effective" => OrderStatus.PartiallyFilled, + "canceled" => OrderStatus.Canceled, + "order_failed" or "partially_failed" => OrderStatus.Rejected, + _ => OrderStatus.Submitted, + }; + var size = Number(o, "sz") ?? 0m; + return new BrokerOrder(Text(o, "algoClOrdId") ?? "", Text(o, "algoId"), Text(o, "instId") ?? "", Text(o, "side") == "sell" ? OrderSide.Sell : OrderSide.Buy, + OrderKind.Stop, size, status, status == OrderStatus.Filled ? Number(o, "actualSz") ?? size : 0m, Millis(Text(o, "uTime") ?? Text(o, "cTime") ?? "0")) + { + StopPrice = Number(o, "triggerPx"), + TimeInForce = TimeInForce.Gtc, + Reason = Text(o, "failCode") is { Length: > 0 } fail && fail != "0" ? "okx_" + fail : null, + }; + } + + /// A fill: the fee is negative when paid, so it is turned into a positive cost (API-NOTES). + public static BrokerFill ReadFill(JsonElement f, string clientOrderId) => new( + Text(f, "instId") + ":" + Text(f, "tradeId"), + clientOrderId, + Text(f, "instId")!, + Text(f, "side") == "sell" ? OrderSide.Sell : OrderSide.Buy, + Number(f, "fillSz") ?? 0m, + Number(f, "fillPx") ?? 0m, + -(Number(f, "fee") ?? 0m), + Text(f, "feeCcy") ?? "", + Millis(Text(f, "fillTime") ?? Text(f, "ts")!)); + + /// An ordinary spot order. Market orders count base coins and never shrink in silence (banAmend). + public static string OrderBody(OrderRequest request) + { + ArgumentNullException.ThrowIfNull(request); + var type = request.Kind switch + { + OrderKind.Market => "market", + _ when request.PostOnly => "post_only", + _ when request.TimeInForce == TimeInForce.Ioc => "ioc", + _ => "limit", + }; + var body = new Dictionary + { + ["instId"] = request.Symbol, + ["tdMode"] = "cash", + ["side"] = Wire.Text(request.Side), + ["ordType"] = type, + ["sz"] = Wire.Number(request.Quantity), + ["clOrdId"] = request.ClientOrderId, + }; + if (request.Kind == OrderKind.Market) + { + body["tgtCcy"] = "base_ccy"; + body["banAmend"] = true; + } + else + { + body["px"] = Wire.Number(request.LimitPrice ?? throw new ArgumentException("A limit order needs a price.", nameof(request))); + } + + return JsonSerializer.Serialize(body); + } + + /// A protective stop: a trigger on the last price that sends a market sale (orderPx -1). + public static string AlgoBody(OrderRequest request) + { + ArgumentNullException.ThrowIfNull(request); + return JsonSerializer.Serialize(new Dictionary + { + ["instId"] = request.Symbol, + ["tdMode"] = "cash", + ["side"] = Wire.Text(request.Side), + ["ordType"] = "trigger", + ["sz"] = Wire.Number(request.Quantity), + ["triggerPx"] = Wire.Number(request.StopPrice ?? throw new ArgumentException("A stop needs a level.", nameof(request))), + ["orderPx"] = "-1", + ["triggerPxType"] = "last", + ["algoClOrdId"] = request.ClientOrderId, + }); + } + + private static bool IsStop(string clientOrderId) => ClientOrderIds.Parse(clientOrderId)?.Purpose == OrderPurpose.Stop; + + private async Task AlgoClientIdAsync(string instrument, string orderId, CancellationToken cancellationToken) + { + var data = await CallAsync(HttpMethod.Get, $"/api/v5/trade/order?instId={Uri.EscapeDataString(instrument)}&ordId={Uri.EscapeDataString(orderId)}", null, _trade, cancellationToken) + .ConfigureAwait(false); + return data.Count == 0 ? null : Text(data[0], "algoClOrdId") is { Length: > 0 } id ? id : Text(data[0], "clOrdId"); + } + + private async Task> BalancesAsync(CancellationToken cancellationToken) + { + var data = await CallAsync(HttpMethod.Get, "/api/v5/account/balance", null, _read, cancellationToken).ConfigureAwait(false); + var balances = new Dictionary(StringComparer.Ordinal); + foreach (var detail in data.Count == 0 ? [] : data[0].GetProperty("details").EnumerateArray().ToList()) + { + balances[Text(detail, "ccy")!] = Number(detail, "cashBal") ?? 0m; + } + + return balances; + } + + private async Task> CallAsync(HttpMethod method, string path, string? body, RateLimiter limiter, CancellationToken cancellationToken) + { + var url = new Uri(_options.RestUrl, path); + var answer = await _http.SendAsync(method, url, body, b => Sign(method.Method, path, b), limiter, retry: method == HttpMethod.Get, cancellationToken).ConfigureAwait(false); + var (code, _, data) = Envelope(answer); + if (code != "0") + { + throw _http.Failure(url, answer); + } + + return data; + } + + private Dictionary Sign(string method, string path, string body) => + OkxSigner.Headers(_credentials, _clock.UtcNow, method, path, body, _options.Demo); + + private static (string Code, string Message, List Data) Envelope(HttpAnswer answer) + { + try + { + using var json = JsonDocument.Parse(answer.Body); + var root = json.RootElement; + var data = root.TryGetProperty("data", out var d) && d.ValueKind == JsonValueKind.Array ? d.EnumerateArray().Select(e => e.Clone()).ToList() : []; + return (Text(root, "code") ?? "?", Text(root, "msg") ?? "", data); + } + catch (JsonException) + { + return ("?", answer.Body, []); + } + } + + private static DateTimeOffset Millis(string text) => + DateTimeOffset.FromUnixTimeMilliseconds(long.Parse(string.IsNullOrEmpty(text) ? "0" : text, CultureInfo.InvariantCulture)); + + private static string? Text(JsonElement e, string name) => + e.ValueKind == JsonValueKind.Object && e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null; + + private static decimal? Number(JsonElement e, string name) => + Text(e, name) is { Length: > 0 } text && decimal.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var d) ? d : null; +} diff --git a/src/Anubis/Trading/OrderManager.Protection.cs b/src/Anubis/Trading/OrderManager.Protection.cs new file mode 100644 index 0000000..9ad618f --- /dev/null +++ b/src/Anubis/Trading/OrderManager.Protection.cs @@ -0,0 +1,325 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; + +namespace Anubis.Trading; + +/// What the stop already passed rule decides (SPEC 7.2). +public enum StopCheck +{ + /// The price is above the level: the stop goes on the broker. + Clear, + + /// The price is at or below the level, confirmed: the uncovered quantity is sold at market. + Breached, + + /// A split was just applied: levels changed, look again at the next turn. + Wait, + + /// + /// The price is missing, old or unconfirmed, or the market is closed: the bot does not sell on its own, and the + /// stop goes on the broker, which triggers it on the real price (at the open, if the market is closed). + /// + Unknown, +} + +/// +/// Protective stops (SPEC 7.2): on the broker as soon as a purchase ends, shaped by the venue (one trigger order on +/// OKX; on Alpaca a GTC stop for the whole shares and a day stop for the fraction, put back at every open), always +/// for the quantity held, checked against the stop already passed rule before every placement. +/// +public sealed partial class OrderManager +{ + /// The stop orders a quantity needs on this venue: quantity and validity. + public IReadOnlyList<(decimal Quantity, TimeInForce TimeInForce)> DesiredStops(Instrument instrument, decimal held) + { + ArgumentNullException.ThrowIfNull(instrument); + var quantity = OrderRules.RoundDown(held, OrderRules.LotOf(instrument.Spec)); + if (quantity <= 0m) + { + return []; + } + + if (!_broker.Capabilities.FractionalStopsAreDayOnly || instrument.IsCrypto) + { + return [(quantity, TimeInForce.Gtc)]; + } + + var (whole, fraction) = OrderRules.SplitWhole(quantity); + var stops = new List<(decimal, TimeInForce)>(); + if (whole > 0m) + { + stops.Add((whole, TimeInForce.Gtc)); + } + + if (fraction > 0m) + { + stops.Add((fraction, TimeInForce.Day)); + } + + return stops; + } + + /// Aligns the stops of every position of the account to the quantity held (SPEC 7.2, 7.4). + public async Task AlignStopsAsync(CancellationToken cancellationToken) + { + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + await AlignStopsCoreAsync(cancellationToken).ConfigureAwait(false); + } + finally + { + _gate.Release(); + } + } + + /// The stop already passed rule (SPEC 7.2): last price at most 60 s old, confirmed by a second reading. + public async Task CheckStopAsync(Instrument instrument, decimal level, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(instrument); + var first = await _quotes(instrument.Symbol, cancellationToken).ConfigureAwait(false); + if (first is null || _clock.UtcNow - first.At > TimeSpan.FromSeconds(60) || first.Bid <= 0m) + { + return StopCheck.Unknown; + } + + if (first.Bid > level) + { + return StopCheck.Clear; + } + + var second = ConfirmPrice is null ? first : await ConfirmPrice(instrument.Symbol, cancellationToken).ConfigureAwait(false); + if (second is null || second.Bid <= 0m) + { + return StopCheck.Unknown; + } + + if (second.Bid > level) + { + return StopCheck.Clear; + } + + if (second.Bid < level * 0.7m && PendingSplit is not null && await PendingSplit(instrument, cancellationToken).ConfigureAwait(false) is { } split) + { + // Far below the level: a split not yet applied explains it, not a crash (SPEC 6.10). + await ApplySplitCoreAsync(instrument, split, cancellationToken).ConfigureAwait(false); + return StopCheck.Wait; + } + + if (MarketOpen is not null && !await MarketOpen(instrument, cancellationToken).ConfigureAwait(false)) + { + // With the market closed the sale leaves at the open: the broker's stop does exactly that. + return StopCheck.Unknown; + } + + return StopCheck.Breached; + } + + /// + /// A split applied to ledger and stops (SPEC 6.10): quantities times the ratio, prices and levels divided. The + /// action is marked as applied, so it is never applied twice. + /// + public async Task ApplySplitAsync(Instrument instrument, CorporateAction split, CancellationToken cancellationToken) + { + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + await ApplySplitCoreAsync(instrument, split, cancellationToken).ConfigureAwait(false); + } + finally + { + _gate.Release(); + } + } + + private async Task ApplySplitCoreAsync(Instrument instrument, CorporateAction split, CancellationToken cancellationToken) + { + if (!split.ChangesShares) + { + return; + } + + var applied = await _ledger.ApplySplitAsync(_account.AccountId, instrument.Id, split.SourceKey, split.Ratio!.Value, cancellationToken).ConfigureAwait(false); + if (!applied) + { + return; + } + + foreach (var position in (await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false)).Where(p => p.InstrumentId == instrument.Id)) + { + await CancelStopsOfAsync(instrument.Id, position.Strategy, instrument, cancellationToken).ConfigureAwait(false); + } + + await _db.WriteAsync(s => Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "split_applied", + $"Frazionamento di {instrument.Symbol} ({Format.Quantity(split.Ratio!.Value)} per 1): ho aggiornato quantità, prezzi medi e stop.", null, cancellationToken), cancellationToken).ConfigureAwait(false); + } + + private async Task AlignStopsCoreAsync(CancellationToken cancellationToken) + { + var positions = await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false); + var withStops = await _db.ReadAsync(s => s.QueryAsync( + "SELECT DISTINCT instrument_id, strategy FROM orders WHERE account_id = @a AND purpose = 'stop' AND status IN ('created', 'submitted', 'partially_filled')", + r => (Instrument: r.Id("instrument_id"), Strategy: r.Text("strategy")), ("a", _account.AccountId)), cancellationToken).ConfigureAwait(false); + var keys = positions.Select(p => (Instrument: p.InstrumentId, p.Strategy)).Union(withStops).ToList(); + foreach (var (instrumentId, strategy) in keys) + { + if (await _instruments(instrumentId, cancellationToken).ConfigureAwait(false) is { } instrument) + { + await AlignPositionAsync(instrumentId, strategy, instrument, cancellationToken).ConfigureAwait(false); + } + } + } + + private async Task AlignPositionAsync(Guid instrumentId, string strategy, Instrument instrument, CancellationToken cancellationToken) + { + var working = await _db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM executions WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND status = @w", + ("a", _account.AccountId), ("i", instrumentId), ("s", strategy), ("w", ExecutionStates.Working)), cancellationToken).ConfigureAwait(false); + if (working > 0) + { + // An execution in progress owns the stops of its position until it ends. + return; + } + + var position = await _ledger.PositionAsync(_account.AccountId, instrumentId, strategy, cancellationToken).ConfigureAwait(false); + var open = await OpenStopsAsync(instrumentId, strategy, cancellationToken).ConfigureAwait(false); + foreach (var unconfirmed in open.Where(o => o.Status == OrderStatus.Created).ToList()) + { + var remote = await _broker.GetOrderAsync(unconfirmed.ClientOrderId, instrument.Symbol, cancellationToken).ConfigureAwait(false); + if (remote is null) + { + await SendStopAsync(unconfirmed, instrument, cancellationToken).ConfigureAwait(false); + } + else + { + await ApplyRemoteAsync(unconfirmed, remote, "found after a lost answer", cancellationToken).ConfigureAwait(false); + } + } + + open = await OpenStopsAsync(instrumentId, strategy, cancellationToken).ConfigureAwait(false); + if (position is null || position.Quantity <= 0m || position.StopPrice is null) + { + await CancelStopsOfAsync(instrumentId, strategy, instrument, cancellationToken).ConfigureAwait(false); + return; + } + + var level = OrderRules.StopPrice(position.StopPrice.Value, instrument.Spec.TickSize); + var desired = DesiredStops(instrument, position.Quantity); + var current = open.Select(o => (o.Quantity - o.Filled, o.TimeInForce)).OrderBy(x => x.Item1).ToList(); + if (open.All(o => o.Stop == level) && current.SequenceEqual(desired.OrderBy(x => x.Quantity))) + { + return; + } + + switch (await CheckStopAsync(instrument, position.StopPrice.Value, cancellationToken).ConfigureAwait(false)) + { + case StopCheck.Wait: + return; + case StopCheck.Breached: + if (await ClearStopsCoreAsync(instrumentId, strategy, instrument, cancellationToken).ConfigureAwait(false)) + { + await ProtectiveSaleAsync(instrumentId, strategy, position.Quantity, "stop_already_passed", cancellationToken).ConfigureAwait(false); + } + + return; + } + + if (!await ClearStopsCoreAsync(instrumentId, strategy, instrument, cancellationToken).ConfigureAwait(false)) + { + return; + } + + var key = ClientOrderIds.Key(StopKey(instrumentId, strategy)); + var sequence = await NextStopSequenceAsync(instrumentId, strategy, key, cancellationToken).ConfigureAwait(false); + foreach (var (quantity, tif) in desired) + { + var clientId = ClientOrderIds.Build(_installation, _account.Environment, strategy, OrderPurpose.Stop, key, sequence++); + var row = new OrderRow(Ids.NewId(_clock), null, instrumentId, strategy, clientId, OrderSide.Sell, OrderKind.Stop, OrderPurpose.Stop, quantity, null, level, + OrderStatus.Created, 0m, null, level, null, tif, false, _clock.UtcNow); + await _db.WriteAsync(s => InsertOrderAsync(s, row, cancellationToken), cancellationToken).ConfigureAwait(false); + await SendStopAsync(row, instrument, cancellationToken).ConfigureAwait(false); + } + } + + private async Task SendStopAsync(OrderRow row, Instrument instrument, CancellationToken cancellationToken) + { + var request = new OrderRequest(row.ClientOrderId, instrument.Symbol, OrderSide.Sell, OrderKind.Stop, row.Quantity, row.TimeInForce) { StopPrice = row.Stop }; + try + { + var remote = await _broker.SubmitOrderAsync(request, cancellationToken).ConfigureAwait(false); + await _db.WriteAsync(s => s.ExecuteAsync("UPDATE orders SET broker_order_id = @b, submitted_at = @now WHERE id = @id", cancellationToken, + ("b", remote.BrokerOrderId), ("now", _clock.UtcNow), ("id", row.Id)), cancellationToken).ConfigureAwait(false); + await ApplyRemoteAsync(row, remote, "stop placed", cancellationToken).ConfigureAwait(false); + } + catch (OrderRejectedException ex) + { + await MoveAsync(row, OrderStatus.Rejected, 0m, null, ex.Code, cancellationToken).ConfigureAwait(false); + await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "stop_rejected", + $"{_account.Name} ha rifiutato lo stop di {instrument.Symbol} ({ex.Code}): sorveglio io il livello e riprovo al prossimo controllo.", cancellationToken), cancellationToken) + .ConfigureAwait(false); + } + catch (BrokerException ex) when (ex.Retryable) + { + await _db.WriteAsync(s => s.ExecuteAsync("UPDATE orders SET reason = 'send_unconfirmed' WHERE id = @id", cancellationToken, ("id", row.Id)), cancellationToken).ConfigureAwait(false); + } + } + + /// Cancels the open stops of a position and confirms it with the broker. True when none is left open. + private async Task ClearStopsCoreAsync(Guid instrumentId, string strategy, Instrument instrument, CancellationToken cancellationToken) + { + await CancelStopsOfAsync(instrumentId, strategy, instrument, cancellationToken).ConfigureAwait(false); + return (await OpenStopsAsync(instrumentId, strategy, cancellationToken).ConfigureAwait(false)).Count == 0; + } + + private async Task CancelStopsOfAsync(Guid instrumentId, string strategy, Instrument instrument, CancellationToken cancellationToken) + { + foreach (var stop in await OpenStopsAsync(instrumentId, strategy, cancellationToken).ConfigureAwait(false)) + { + await _broker.CancelOrderAsync(stop.ClientOrderId, instrument.Symbol, cancellationToken).ConfigureAwait(false); + var remote = await _broker.GetOrderAsync(stop.ClientOrderId, instrument.Symbol, cancellationToken).ConfigureAwait(false); + if (remote is null && stop.Status == OrderStatus.Created) + { + await MoveAsync(stop, OrderStatus.Canceled, 0m, null, "never reached the broker", cancellationToken).ConfigureAwait(false); + } + else if (remote is not null) + { + await ApplyRemoteAsync(stop, remote, "stop canceled", cancellationToken).ConfigureAwait(false); + } + } + } + + /// A protective sale at market (SPEC 7.2): outside the pace, also in pause and with "stop everything". + private async Task ProtectiveSaleAsync(Guid instrumentId, string strategy, decimal quantity, string reason, CancellationToken cancellationToken) + { + var already = await _db.ReadAsync(s => s.CountAsync( + "SELECT COUNT(*) FROM executions WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND status = @w AND side = 'sell'", + ("a", _account.AccountId), ("i", instrumentId), ("s", strategy), ("w", ExecutionStates.Working)), cancellationToken).ConfigureAwait(false); + if (already > 0) + { + return; + } + + await SubmitAsync(new TradeIntent(instrumentId, strategy, OrderSide.Sell, quantity, OrderPurpose.Protective, Ids.NewId(_clock)), cancellationToken).ConfigureAwait(false); + var instrument = await _instruments(instrumentId, cancellationToken).ConfigureAwait(false); + await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, reason, + $"Lo stop di {instrument?.Symbol} su {_account.Name} è superato: vendo subito a mercato {Format.Quantity(quantity)}.", cancellationToken), cancellationToken).ConfigureAwait(false); + } + + private Task> OpenStopsAsync(Guid instrumentId, string strategy, CancellationToken cancellationToken) => + _db.ReadAsync(s => s.QueryAsync(OrderSelect + " WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND purpose = 'stop' AND status IN ('created', 'submitted', 'partially_filled')", + ReadOrder, ("a", _account.AccountId), ("i", instrumentId), ("s", strategy)), cancellationToken); + + private async Task NextStopSequenceAsync(Guid instrumentId, string strategy, string key, CancellationToken cancellationToken) + { + var ids = await _db.ReadAsync(s => s.QueryAsync("SELECT client_order_id FROM orders WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND purpose = 'stop'", + r => r.Text("client_order_id"), ("a", _account.AccountId), ("i", instrumentId), ("s", strategy)), cancellationToken).ConfigureAwait(false); + return ids.Select(ClientOrderIds.Parse).Where(p => p is not null && p.Key == key).Select(p => p!.Sequence).DefaultIfEmpty(0).Max() + 1; + } + + /// A stable id for the stops of a position: account, instrument and strategy. + private Guid StopKey(Guid instrumentId, string strategy) + { + var bytes = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(_account.AccountId.ToString("N") + instrumentId.ToString("N") + strategy)); + return new Guid(bytes.AsSpan(0, 16)); + } +} diff --git a/src/Anubis/Trading/OrderManager.cs b/src/Anubis/Trading/OrderManager.cs new file mode 100644 index 0000000..8a93f2f --- /dev/null +++ b/src/Anubis/Trading/OrderManager.cs @@ -0,0 +1,756 @@ +using System.Globalization; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; + +namespace Anubis.Trading; + +/// What a strategy (or the protection) wants done: buy or sell a quantity of an instrument. +public sealed record TradeIntent(Guid InstrumentId, string Strategy, OrderSide Side, decimal Quantity, OrderPurpose Purpose, Guid DecisionId) +{ + /// Start directly with the aggressive limit (the 15:55 exits of equity_meanrev, SPEC 7.2). + public bool StartAggressive { get; init; } + + /// The protective level of the position: watched during the purchase, placed on the broker after it. + public decimal? StopLevel { get; init; } +} + +/// The account an order manager works on. +public sealed record AccountContext(Guid AccountId, string Name, string Broker, string Environment, string Currency); + +/// States of an execution. +public static class ExecutionStates +{ + public const string Working = "working"; + public const string Done = "done"; + public const string Canceled = "canceled"; +} + +/// +/// At most sends in any minute for an account (SPEC 7.2). Protective sales and stops do +/// not use it: they have their own way. +/// +public sealed class SendPacer(IClock clock, int perMinute = 6) +{ + private readonly Queue _sent = new(); + + public int PerMinute { get; } = perMinute; + + public int Available + { + get + { + Trim(); + return PerMinute - _sent.Count; + } + } + + public bool TryTake() + { + Trim(); + if (_sent.Count >= PerMinute) + { + return false; + } + + _sent.Enqueue(clock.UtcNow); + return true; + } + + private void Trim() + { + var now = clock.UtcNow; + while (_sent.Count > 0 && now - _sent.Peek() >= TimeSpan.FromMinutes(1)) + { + _sent.Dequeue(); + } + } +} + +/// +/// The order manager of one account (SPEC 7.2): the only way an order reaches a broker. It keeps the explicit +/// state machine with every transition recorded, deterministic client ids, rounding before sending, the chasing +/// limit (three passive steps of 60 s, post-only where the venue has it, then an aggressive limit within a +/// tolerance of the reference price), purchases that give up and sales that never do, the pace of six sends a +/// minute, slippage on every fill and the protective stops that follow the quantity held. It moves on +/// , so the same code runs in the service, in the tests and after a restart: an execution +/// is picked up where it stopped and an order whose answer was lost is looked up before any resend. +/// +public sealed partial class OrderManager : IDisposable +{ + private readonly Database _db; + private readonly IClock _clock; + private readonly Ledger _ledger; + private readonly IBrokerAccount _broker; + private readonly AccountContext _account; + private readonly string _installation; + private readonly Func> _instruments; + private readonly Func> _quotes; + private readonly SemaphoreSlim _gate = new(1, 1); + private readonly SendPacer _pacer; + + public OrderManager(Database db, IClock clock, Ledger ledger, IBrokerAccount broker, AccountContext account, string installationCode, + Func> instruments, Func> quotes) + { + _db = db ?? throw new ArgumentNullException(nameof(db)); + _clock = clock ?? throw new ArgumentNullException(nameof(clock)); + _ledger = ledger ?? throw new ArgumentNullException(nameof(ledger)); + _broker = broker ?? throw new ArgumentNullException(nameof(broker)); + _account = account ?? throw new ArgumentNullException(nameof(account)); + _installation = installationCode; + _instruments = instruments ?? throw new ArgumentNullException(nameof(instruments)); + _quotes = quotes ?? throw new ArgumentNullException(nameof(quotes)); + _pacer = new SendPacer(clock); + if (broker.Environment != account.Environment) + { + throw new ArgumentException("The broker adapter is for another environment.", nameof(broker)); + } + } + + /// How long a step of the chasing limit waits before moving (SPEC 7.2). + public TimeSpan StepTime { get; init; } = TimeSpan.FromSeconds(60); + + public int PassiveSteps { get; init; } = 3; + + /// Restarts of an unfilled sale before the alert: one a minute, so about five minutes. + public int SellRestartsBeforeAlert { get; init; } = 5; + + /// A second reading of the last price through REST, for the stop already passed (SPEC 7.2). + public Func>? ConfirmPrice { get; init; } + + /// The market of an instrument is open now (stocks: the broker's calendar; crypto: always). + public Func>? MarketOpen { get; init; } + + /// A split of the instrument not yet applied, looked for when the price is far below a stop (SPEC 6.10). + public Func>? PendingSplit { get; init; } + + /// Called after new fills are recorded: the equity is photographed at every execution (SPEC 7.5). + public Func? AfterFills { get; init; } + + public AccountContext Account => _account; + + public IBrokerAccount Broker => _broker; + + public SendPacer Pacer => _pacer; + + /// + /// Accepts an intent as an execution. A new entry on an account in prudent mode is refused with its reason + /// (SPEC 7.4); exits and protection always go ahead. + /// + public async Task<(Guid? Execution, string? Refusal)> SubmitAsync(TradeIntent intent, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(intent); + if (intent.Quantity <= 0m) + { + return (null, OrderReasons.ZeroQuantity); + } + + if (!ClientOrderIds.StrategyCodes.ContainsKey(intent.Strategy)) + { + throw new ArgumentException($"Strategy '{intent.Strategy}' has no order code.", nameof(intent)); + } + + if (intent.Purpose == OrderPurpose.Entry && await IsPrudentAsync(cancellationToken).ConfigureAwait(false)) + { + return (null, OrderReasons.PrudentMode); + } + + var id = Ids.NewId(_clock); + var now = _clock.UtcNow; + await _db.WriteAsync(s => s.ExecuteAsync( + "INSERT INTO executions (id, account_id, instrument_id, strategy, side, purpose, quantity, filled, order_key, sequence, step, stop_level, status, started_at, created_at, updated_at) " + + "VALUES (@id, @a, @i, @s, @side, @p, @q, 0, @k, 0, @step, @stop, @st, @now, @now, @now)", cancellationToken, + ("id", id), ("a", _account.AccountId), ("i", intent.InstrumentId), ("s", intent.Strategy), ("side", Wire.Text(intent.Side)), ("p", Wire.Text(intent.Purpose)), + ("q", intent.Quantity), ("k", ClientOrderIds.Key(intent.DecisionId)), ("step", intent.StartAggressive ? PassiveSteps - 1 : -1), ("stop", intent.StopLevel), + ("st", ExecutionStates.Working), ("now", now)), cancellationToken).ConfigureAwait(false); + return (id, null); + } + + /// One turn of work: fills, order states, the next steps within the pace, stops aligned to what is held. + public async Task TickAsync(CancellationToken cancellationToken) + { + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + await RefreshOpenOrdersAsync(cancellationToken).ConfigureAwait(false); + await SyncFillsCoreAsync(cancellationToken).ConfigureAwait(false); + var plans = new List<(ExecRow Exec, int Priority)>(); + foreach (var exec in await WorkingAsync(cancellationToken).ConfigureAwait(false)) + { + if (await AdvanceAsync(exec, cancellationToken).ConfigureAwait(false) is { } priority) + { + plans.Add((exec, priority)); + } + } + + // Protective sales first and outside the pace; then sales and steps already under way; new buys wait. + foreach (var (exec, priority) in plans.OrderBy(p => p.Priority).ThenBy(p => p.Exec.StartedAt)) + { + if (priority > 0 && !_pacer.TryTake()) + { + continue; + } + + await SendStepAsync(exec, cancellationToken).ConfigureAwait(false); + } + + await SyncFillsCoreAsync(cancellationToken).ConfigureAwait(false); + await AlignStopsCoreAsync(cancellationToken).ConfigureAwait(false); + } + finally + { + _gate.Release(); + } + } + + /// An update from the broker's stream: the order state is recorded at once, fills come with the next query. + public async Task HandleUpdateAsync(OrderUpdate update, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(update); + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + var row = await OrderByClientIdAsync(update.Order.ClientOrderId, cancellationToken).ConfigureAwait(false); + if (row is not null) + { + await ApplyRemoteAsync(row, update.Order, "stream", cancellationToken).ConfigureAwait(false); + } + + if (update.Fill is not null) + { + await SyncFillsCoreAsync(cancellationToken).ConfigureAwait(false); + } + } + finally + { + _gate.Release(); + } + } + + /// Records the broker's fills of this installation's orders, once each. Returns how many were new. + public async Task SyncFillsAsync(CancellationToken cancellationToken) + { + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + return await SyncFillsCoreAsync(cancellationToken).ConfigureAwait(false); + } + finally + { + _gate.Release(); + } + } + + /// The installation's code in client order ids: what tells this bot's orders from the rest. + public string InstallationCode => _installation; + + public Task FindInstrumentAsync(Guid instrumentId, CancellationToken cancellationToken) => _instruments(instrumentId, cancellationToken); + + /// + /// Brings order states and fills up to date without sending anything: what reconciliation does first, because a + /// late fill or a lost update explains most differences (SPEC 7.4). + /// + public async Task RefreshAsync(CancellationToken cancellationToken) + { + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + await RefreshOpenOrdersAsync(cancellationToken).ConfigureAwait(false); + await SyncFillsCoreAsync(cancellationToken).ConfigureAwait(false); + } + finally + { + _gate.Release(); + } + } + + /// + /// An order of this installation that the broker still has open. Known: its state is recorded, and an order + /// the bot already considered closed is canceled, because nothing should be working that the bot does not + /// follow. Unknown: false, and reconciliation reports it. + /// + public async Task AdoptOpenOrderAsync(BrokerOrder remote, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(remote); + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + var row = await OrderByClientIdAsync(remote.ClientOrderId, cancellationToken).ConfigureAwait(false); + if (row is null) + { + return false; + } + + if (OrderStates.IsFinal(row.Status)) + { + await _broker.CancelOrderAsync(remote.ClientOrderId, remote.Symbol, cancellationToken).ConfigureAwait(false); + return true; + } + + await ApplyRemoteAsync(row, remote, "reconciliation", cancellationToken).ConfigureAwait(false); + return true; + } + finally + { + _gate.Release(); + } + } + + /// Instruments with an execution under way on this account: their stops are being moved on purpose. + public Task> WorkingInstrumentsAsync(CancellationToken cancellationToken) => + _db.ReadAsync>(async s => (await s.QueryAsync("SELECT DISTINCT instrument_id FROM executions WHERE account_id = @a AND status = @w", + r => r.Id("instrument_id"), ("a", _account.AccountId), ("w", ExecutionStates.Working)).ConfigureAwait(false)).ToList(), cancellationToken); + + /// The account's open orders in the bot's own table (submitted or partly filled). + public Task> OpenOrdersAsync(CancellationToken cancellationToken) => + _db.ReadAsync>(async s => (await s.QueryAsync(OrderSelect + " WHERE account_id = @a AND status IN ('submitted', 'partially_filled')", + ReadOrder, ("a", _account.AccountId)).ConfigureAwait(false)).Select(o => (o.ClientOrderId, o.InstrumentId, o.Purpose)).ToList(), cancellationToken); + + public Task IsPrudentAsync(CancellationToken cancellationToken) => + _db.ReadAsync(async s => await s.FirstOrDefaultAsync("SELECT mode FROM account_status WHERE account_id = @a", r => r.Text("mode"), ("a", _account.AccountId)).ConfigureAwait(false) == AccountModes.Prudent, + cancellationToken); + + private async Task AdvanceAsync(ExecRow exec, CancellationToken cancellationToken) + { + var instrument = await _instruments(exec.InstrumentId, cancellationToken).ConfigureAwait(false) + ?? throw new InvalidOperationException("Unknown instrument " + exec.InstrumentId); + var orders = await ExecutionOrdersAsync(exec.Id, cancellationToken).ConfigureAwait(false); + var current = orders.LastOrDefault(); + if (current is not null && !OrderStates.IsFinal(current.Status)) + { + if (current.Status == OrderStatus.Created) + { + // The answer to the send was lost: ask the broker before anything else (SPEC 7.2). + var remote = await _broker.GetOrderAsync(current.ClientOrderId, instrument.Symbol, cancellationToken).ConfigureAwait(false); + if (remote is null) + { + return exec.Purpose == OrderPurpose.Protective ? 0 : 1; + } + + await ApplyRemoteAsync(current, remote, "found after a lost answer", cancellationToken).ConfigureAwait(false); + return null; + } + + if (exec.Side == OrderSide.Buy && exec.StopLevel is { } level && await _quotes(instrument.Symbol, cancellationToken).ConfigureAwait(false) is { } quote && quote.Bid <= level) + { + // The level is watched by the bot while the purchase is in progress: touched, the purchase stops. + await CancelAndReadAsync(current, instrument, "stop level touched during the purchase", cancellationToken).ConfigureAwait(false); + await FinishAsync(exec, ExecutionStates.Canceled, "stop_touched", instrument, cancellationToken).ConfigureAwait(false); + return null; + } + + if (current.Kind != OrderKind.Market && exec.StepStartedAt is { } started && _clock.UtcNow - started >= StepTime) + { + await CancelAndReadAsync(current, instrument, "step time over", cancellationToken).ConfigureAwait(false); + } + + return null; + } + + var filled = orders.Sum(o => o.Filled); + var remaining = exec.Quantity - filled; + if (exec.Side == OrderSide.Sell) + { + // Never sell more than the ledger holds: a stop may have sold part of it meanwhile. + var held = (await _ledger.PositionAsync(_account.AccountId, exec.InstrumentId, exec.Strategy, cancellationToken).ConfigureAwait(false))?.Quantity ?? 0m; + remaining = Math.Min(remaining, held); + } + + var quoteNow = await _quotes(instrument.Symbol, cancellationToken).ConfigureAwait(false); + var price = quoteNow?.Mid ?? exec.Reference ?? 0m; + var rounded = OrderRules.Round(instrument.Spec, exec.Side, OrderKind.Limit, remaining, price); + if (remaining <= Ledger.Dust || (price > 0m && rounded.Rejection is OrderReasons.BelowMinimumSize or OrderReasons.BelowMinimumNotional or OrderReasons.ZeroQuantity)) + { + await FinishAsync(exec, ExecutionStates.Done, remaining <= Ledger.Dust ? "filled" : "rest_below_minimum", instrument, cancellationToken).ConfigureAwait(false); + return null; + } + + var next = exec.Step + 1; + if (exec.Purpose != OrderPurpose.Protective && next > PassiveSteps && exec.Side == OrderSide.Buy) + { + // Not even the aggressive limit filled: a purchase is given up (SPEC 7.2). + await FinishAsync(exec, ExecutionStates.Canceled, "not_filled", instrument, cancellationToken).ConfigureAwait(false); + return null; + } + + if (exec.Side == OrderSide.Sell && exec.Step < 0 && !await ClearStopsCoreAsync(exec.InstrumentId, exec.Strategy, instrument, cancellationToken).ConfigureAwait(false)) + { + // The stops on the quantity to sell must be gone first (SPEC 7.2); they come back if the sale stops. + return null; + } + + if (exec.Side == OrderSide.Buy && exec.Step < 0 && _broker.Capabilities.OppositeSideBlocked + && !await ClearStopsCoreAsync(exec.InstrumentId, exec.Strategy, instrument, cancellationToken).ConfigureAwait(false)) + { + // Alpaca refuses a purchase while a sell stop rests on the symbol: cancel, buy, put back. + return null; + } + + if (quoteNow is null) + { + return null; + } + + return exec.Purpose == OrderPurpose.Protective ? 0 : exec.Side == OrderSide.Sell || exec.Step >= 0 ? 1 : 2; + } + + private async Task SendStepAsync(ExecRow exec, CancellationToken cancellationToken) + { + var instrument = (await _instruments(exec.InstrumentId, cancellationToken).ConfigureAwait(false))!; + var orders = await ExecutionOrdersAsync(exec.Id, cancellationToken).ConfigureAwait(false); + var current = orders.LastOrDefault(); + if (current is { Status: OrderStatus.Created }) + { + // A resend after a network error: same id, so it cannot create a duplicate. + await SendAsync(exec, current, instrument, cancellationToken).ConfigureAwait(false); + return; + } + + var quote = await _quotes(instrument.Symbol, cancellationToken).ConfigureAwait(false); + if (quote is null) + { + return; + } + + var step = exec.Step + 1; + var reference = exec.Reference ?? quote.Mid; + var tolerance = exec.Tolerance ?? BaseTolerance(instrument); + if (exec.Side == OrderSide.Sell && step > PassiveSteps) + { + // A sale never given up: every minute a new reference from the current price, with double tolerance. + reference = quote.Mid; + tolerance = BaseTolerance(instrument) * 2m; + } + + var filled = orders.Sum(o => o.Filled); + var remaining = exec.Quantity - filled; + if (exec.Side == OrderSide.Sell) + { + var held = (await _ledger.PositionAsync(_account.AccountId, exec.InstrumentId, exec.Strategy, cancellationToken).ConfigureAwait(false))?.Quantity ?? 0m; + remaining = Math.Min(remaining, held); + } + + OrderKind kind; + decimal? limit = null; + var postOnly = false; + var tif = instrument.Venue == Venues.Alpaca ? TimeInForce.Day : TimeInForce.Gtc; + if (exec.Purpose == OrderPurpose.Protective) + { + kind = OrderKind.Market; + } + else if (step < PassiveSteps) + { + kind = OrderKind.Limit; + limit = exec.Side == OrderSide.Buy ? quote.Bid : quote.Ask; + postOnly = _broker.Capabilities.PostOnly; + } + else + { + kind = OrderKind.Limit; + limit = exec.Side == OrderSide.Buy ? reference * (1m + tolerance) : reference * (1m - tolerance); + } + + var rounded = OrderRules.Round(instrument.Spec, exec.Side, kind, remaining, quote.Mid, limit); + if (!rounded.IsValid) + { + await FinishAsync(exec, exec.Side == OrderSide.Buy ? ExecutionStates.Canceled : ExecutionStates.Done, rounded.Rejection!, instrument, cancellationToken).ConfigureAwait(false); + return; + } + + var sequence = exec.Sequence + 1; + var clientId = ClientOrderIds.Build(_installation, _account.Environment, exec.Strategy, exec.Purpose, exec.Key, sequence); + var now = _clock.UtcNow; + var row = new OrderRow(Ids.NewId(_clock), exec.Id, exec.InstrumentId, exec.Strategy, clientId, exec.Side, kind, exec.Purpose, rounded.Quantity, rounded.LimitPrice, null, + OrderStatus.Created, 0m, null, reference, step, tif, postOnly, now); + await _db.WriteAsync(async s => + { + await InsertOrderAsync(s, row, cancellationToken).ConfigureAwait(false); + await s.ExecuteAsync("UPDATE executions SET sequence = @q, step = @step, reference_price = @r, tolerance = @t, step_started_at = @now, updated_at = @now WHERE id = @id", + cancellationToken, ("q", sequence), ("step", step), ("r", reference), ("t", tolerance), ("now", now), ("id", exec.Id)).ConfigureAwait(false); + if (exec.Side == OrderSide.Sell && step == PassiveSteps + 1 + SellRestartsBeforeAlert && exec.AlertedAt is null) + { + await s.ExecuteAsync("UPDATE executions SET alerted_at = @now WHERE id = @id", cancellationToken, ("now", now), ("id", exec.Id)).ConfigureAwait(false); + await Diary.NotifyAsync(s, _clock, "sell_not_filled", + $"Non riesco a vendere {instrument.Symbol} da cinque minuti su {_account.Name}: continuo a provare ogni minuto con un prezzo aggiornato.", cancellationToken).ConfigureAwait(false); + } + }, cancellationToken).ConfigureAwait(false); + await SendAsync(exec, row, instrument, cancellationToken).ConfigureAwait(false); + } + + private async Task SendAsync(ExecRow exec, OrderRow row, Instrument instrument, CancellationToken cancellationToken) + { + var request = new OrderRequest(row.ClientOrderId, instrument.Symbol, row.Side, row.Kind, row.Quantity, row.TimeInForce) + { + LimitPrice = row.Limit, + StopPrice = row.Stop, + PostOnly = row.PostOnly, + }; + try + { + var remote = await _broker.SubmitOrderAsync(request, cancellationToken).ConfigureAwait(false); + await _db.WriteAsync(s => s.ExecuteAsync("UPDATE orders SET broker_order_id = @b, submitted_at = @now WHERE id = @id", cancellationToken, + ("b", remote.BrokerOrderId), ("now", _clock.UtcNow), ("id", row.Id)), cancellationToken).ConfigureAwait(false); + await ApplyRemoteAsync(row, remote, "sent", cancellationToken).ConfigureAwait(false); + } + catch (OrderRejectedException ex) + { + await MoveAsync(row, OrderStatus.Rejected, 0m, null, ex.Code, cancellationToken).ConfigureAwait(false); + await _db.WriteAsync(s => Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "order_rejected", + $"{_account.Name} ha rifiutato un ordine su {instrument.Symbol} ({ex.Code}).", new { row.ClientOrderId, ex.Code }, cancellationToken), cancellationToken).ConfigureAwait(false); + if (exec.Side == OrderSide.Buy && ex.Code is not ("okx_51006" or "post_only_would_take")) + { + await FinishAsync(exec, ExecutionStates.Canceled, "rejected_" + ex.Code, instrument, cancellationToken).ConfigureAwait(false); + } + } + catch (BrokerException ex) when (ex.Retryable) + { + // The answer is lost: the order stays "created" and the next turn asks the broker before resending. + await _db.WriteAsync(s => s.ExecuteAsync("UPDATE orders SET reason = @r, updated_at = @now WHERE id = @id", cancellationToken, + ("r", "send_unconfirmed"), ("now", _clock.UtcNow), ("id", row.Id)), cancellationToken).ConfigureAwait(false); + } + } + + private async Task CancelAndReadAsync(OrderRow row, Instrument instrument, string why, CancellationToken cancellationToken) + { + await _broker.CancelOrderAsync(row.ClientOrderId, instrument.Symbol, cancellationToken).ConfigureAwait(false); + var remote = await _broker.GetOrderAsync(row.ClientOrderId, instrument.Symbol, cancellationToken).ConfigureAwait(false); + if (remote is not null) + { + await ApplyRemoteAsync(row, remote, why, cancellationToken).ConfigureAwait(false); + } + } + + private async Task FinishAsync(ExecRow exec, string status, string reason, Instrument instrument, CancellationToken cancellationToken) + { + var now = _clock.UtcNow; + await _db.WriteAsync(s => s.ExecuteAsync("UPDATE executions SET status = @s, reason = @r, finished_at = @now, updated_at = @now WHERE id = @id", cancellationToken, + ("s", status), ("r", reason), ("now", now), ("id", exec.Id)), cancellationToken).ConfigureAwait(false); + if (exec.Side == OrderSide.Buy && exec.StopLevel is { } level) + { + var position = await _ledger.PositionAsync(_account.AccountId, exec.InstrumentId, exec.Strategy, cancellationToken).ConfigureAwait(false); + if (position is not null) + { + await _ledger.SetStopAsync(_account.AccountId, exec.InstrumentId, exec.Strategy, level, cancellationToken).ConfigureAwait(false); + } + } + + if (exec.Side == OrderSide.Sell && exec.Purpose is OrderPurpose.Exit or OrderPurpose.Protective) + { + await WriteOffResidueAsync(exec.InstrumentId, exec.Strategy, instrument, cancellationToken).ConfigureAwait(false); + } + + // Stops follow the quantity held, however the execution ended (SPEC 7.2). + await AlignPositionAsync(exec.InstrumentId, exec.Strategy, instrument, cancellationToken).ConfigureAwait(false); + } + + private async Task WriteOffResidueAsync(Guid instrumentId, string strategy, Instrument instrument, CancellationToken cancellationToken) + { + var position = await _ledger.PositionAsync(_account.AccountId, instrumentId, strategy, cancellationToken).ConfigureAwait(false); + if (position is null || position.Quantity <= 0m) + { + return; + } + + var quote = await _quotes(instrument.Symbol, cancellationToken).ConfigureAwait(false); + var price = quote?.Bid ?? position.LastPrice ?? position.AveragePrice; + if (!OrderRules.IsUnsellable(instrument.Spec, position.Quantity, price)) + { + return; + } + + await _ledger.WriteOffResidueAsync(_account.AccountId, instrumentId, strategy, price, "below_minimum", cancellationToken).ConfigureAwait(false); + await CancelStopsOfAsync(instrumentId, strategy, instrument, cancellationToken).ConfigureAwait(false); + await _db.WriteAsync(s => Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "residue_written_off", + $"Su {_account.Name} restano {Format.Quantity(position.Quantity)} {instrument.Symbol}, sotto il minimo vendibile: li tolgo dal registro al valore di mercato e li mostro a parte.", + null, cancellationToken), cancellationToken).ConfigureAwait(false); + } + + private async Task SyncFillsCoreAsync(CancellationToken cancellationToken) + { + var since = await _db.ReadAsync(async s => + { + var last = (await s.QueryAsync("SELECT executed_at FROM fills WHERE account_id = @a AND execution_id NOT LIKE 'ANU%'", r => r.Moment("executed_at"), ("a", _account.AccountId)) + .ConfigureAwait(false)).DefaultIfEmpty(DateTimeOffset.MinValue).Max(); + var firstOrder = (await s.QueryAsync("SELECT created_at FROM orders WHERE account_id = @a", r => r.Moment("created_at"), ("a", _account.AccountId)).ConfigureAwait(false)) + .DefaultIfEmpty(_clock.UtcNow).Min(); + return last == DateTimeOffset.MinValue ? firstOrder.AddMinutes(-10) : last.AddMinutes(-10); + }, cancellationToken).ConfigureAwait(false); + var fills = await _broker.GetFillsAsync(since, cancellationToken).ConfigureAwait(false); + var recorded = 0; + foreach (var fill in fills.OrderBy(f => f.ExecutedAt)) + { + if (!ClientOrderIds.IsOurs(fill.ClientOrderId, _installation)) + { + continue; + } + + var row = await OrderByClientIdAsync(fill.ClientOrderId, cancellationToken).ConfigureAwait(false); + if (row is null) + { + continue; + } + + FillOutcome outcome; + try + { + outcome = await _ledger.RecordFillAsync(new LedgerFill(_account.AccountId, row.InstrumentId, row.Strategy, fill.ExecutionId, fill.Side, fill.Quantity, fill.Price, + fill.Fee, fill.FeeCurrency, fill.ExecutedAt) + { + OrderId = row.Id, + ReferencePrice = row.Purpose == OrderPurpose.Stop ? row.Stop : row.Reference, + ExitReason = row.Purpose is OrderPurpose.Stop or OrderPurpose.Protective ? "stop" : "exit", + }, cancellationToken).ConfigureAwait(false); + } + catch (LedgerException ex) + { + await _db.WriteAsync(s => Diary.NotifyAsync(s, _clock, "ledger_refused_fill", + $"Un'esecuzione su {_account.Name} non torna con il mio registro: la controllo nella riconciliazione. ({ex.Message})", cancellationToken), cancellationToken).ConfigureAwait(false); + continue; + } + + if (!outcome.Recorded) + { + continue; + } + + recorded++; + var instrument = await _instruments(row.InstrumentId, cancellationToken).ConfigureAwait(false); + await _db.WriteAsync(s => Diary.WriteAsync(s, _clock, DiaryKinds.Orders, "fill", + string.Create(CultureInfo.InvariantCulture, + $"{(fill.Side == OrderSide.Buy ? "Comprati" : "Venduti")} {Format.Quantity(fill.Quantity)} {instrument?.Symbol} a {Format.Price(fill.Price)} su {_account.Name}."), + new { fill.ExecutionId, row.ClientOrderId, outcome.SlippageBp }, cancellationToken), cancellationToken).ConfigureAwait(false); + if (row.Purpose == OrderPurpose.Stop && outcome.Quantity > 0m && instrument is not null) + { + // A stop that fired only in part, or one of Alpaca's two stops: the rest is sold at once (SPEC 7.2). + await ProtectiveSaleAsync(row.InstrumentId, row.Strategy, outcome.Quantity, "stop_partly_triggered", cancellationToken).ConfigureAwait(false); + } + } + + if (recorded > 0 && AfterFills is not null) + { + await AfterFills(cancellationToken).ConfigureAwait(false); + } + + return recorded; + } + + private async Task RefreshOpenOrdersAsync(CancellationToken cancellationToken) + { + var open = await _db.ReadAsync(s => s.QueryAsync(OrderSelect + " WHERE account_id = @a AND status IN ('submitted', 'partially_filled')", ReadOrder, ("a", _account.AccountId)), + cancellationToken).ConfigureAwait(false); + foreach (var row in open) + { + var instrument = await _instruments(row.InstrumentId, cancellationToken).ConfigureAwait(false); + if (instrument is null) + { + continue; + } + + var remote = await _broker.GetOrderAsync(row.ClientOrderId, instrument.Symbol, cancellationToken).ConfigureAwait(false); + if (remote is null) + { + // OKX forgets a canceled order without fills after two hours (API-NOTES): unknown after that is canceled. + if (_clock.UtcNow - row.CreatedAt > TimeSpan.FromHours(2)) + { + await MoveAsync(row, OrderStatus.Canceled, row.Filled, row.AveragePrice, "unknown_to_broker", cancellationToken).ConfigureAwait(false); + } + + continue; + } + + await ApplyRemoteAsync(row, remote, "query", cancellationToken).ConfigureAwait(false); + } + } + + private async Task ApplyRemoteAsync(OrderRow row, BrokerOrder remote, string note, CancellationToken cancellationToken) + { + var status = remote.Status; + if (row.Status == OrderStatus.Created && status is OrderStatus.PartiallyFilled or OrderStatus.Filled or OrderStatus.Canceled or OrderStatus.Expired) + { + await MoveAsync(row, OrderStatus.Submitted, 0m, null, note, cancellationToken).ConfigureAwait(false); + row = row with { Status = OrderStatus.Submitted }; + } + + if (status == row.Status && remote.FilledQuantity == row.Filled) + { + return; + } + + await MoveAsync(row, status, remote.FilledQuantity, remote.AverageFillPrice, remote.Reason ?? note, cancellationToken).ConfigureAwait(false); + } + + /// One transition of the state machine, recorded (SPEC 7.2). A move backwards is ignored. + private async Task MoveAsync(OrderRow row, OrderStatus to, decimal filled, decimal? average, string note, CancellationToken cancellationToken) + { + if (to != row.Status && !OrderStates.CanMove(row.Status, to)) + { + return; + } + + filled = Math.Max(filled, row.Filled); + var now = _clock.UtcNow; + await _db.WriteAsync(async s => + { + await s.ExecuteAsync( + "UPDATE orders SET status = @st, filled_quantity = @f, average_fill_price = @p, reason = @r, updated_at = @now, closed_at = @c WHERE id = @id", cancellationToken, + ("st", Wire.Text(to)), ("f", filled), ("p", average ?? row.AveragePrice), ("r", note), ("now", now), ("c", OrderStates.IsFinal(to) ? now : null), ("id", row.Id)) + .ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO order_events (id, order_id, from_status, to_status, filled_quantity, note, occurred_at, created_at) VALUES (@id, @o, @f, @t, @q, @n, @now, @now)", + cancellationToken, ("id", Ids.NewId(_clock)), ("o", row.Id), ("f", Wire.Text(row.Status)), ("t", Wire.Text(to)), ("q", filled), ("n", note), ("now", now)).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + } + + private static decimal BaseTolerance(Instrument instrument) + { + if (!instrument.IsCrypto) + { + return 0.003m; + } + + var coin = instrument.Spec.BaseCurrency ?? instrument.Symbol.Split('-', '/')[0]; + return coin is "BTC" or "ETH" or "SOL" ? 0.005m : 0.008m; + } + + private Task> WorkingAsync(CancellationToken cancellationToken) => + _db.ReadAsync(s => s.QueryAsync( + "SELECT id, instrument_id, strategy, side, purpose, quantity, order_key, sequence, step, reference_price, tolerance, stop_level, started_at, step_started_at, alerted_at " + + "FROM executions WHERE account_id = @a AND status = @w ORDER BY started_at, id", + r => new ExecRow(r.Id("id"), r.Id("instrument_id"), r.Text("strategy"), Wire.Side(r.Text("side")), Wire.Purpose(r.Text("purpose")), r.Money("quantity"), + r.Text("order_key"), (int)r.Number("sequence"), (int)r.Number("step"), r.MoneyOrNull("reference_price"), r.MoneyOrNull("tolerance"), r.MoneyOrNull("stop_level"), + r.Moment("started_at"), r.MomentOrNull("step_started_at"), r.MomentOrNull("alerted_at")), + ("a", _account.AccountId), ("w", ExecutionStates.Working)), cancellationToken); + + private Task> ExecutionOrdersAsync(Guid execution, CancellationToken cancellationToken) => + _db.ReadAsync(s => s.QueryAsync(OrderSelect + " WHERE execution_id = @e ORDER BY step, created_at", ReadOrder, ("e", execution)), cancellationToken); + + private Task OrderByClientIdAsync(string clientId, CancellationToken cancellationToken) => + _db.ReadAsync(s => s.FirstOrDefaultAsync(OrderSelect + " WHERE client_order_id = @c AND account_id = @a", ReadOrder, ("c", clientId), ("a", _account.AccountId)), cancellationToken); + + private Task InsertOrderAsync(DbSession s, OrderRow row, CancellationToken cancellationToken) => s.ExecuteAsync( + "INSERT INTO orders (id, account_id, instrument_id, strategy, client_order_id, side, order_type, quantity, limit_price, stop_price, status, created_at, updated_at, " + + "purpose, time_in_force, post_only, reference_price, filled_quantity, step, execution_id) " + + "VALUES (@id, @a, @i, @s, @c, @side, @k, @q, @l, @st, 'created', @now, @now, @p, @tif, @po, @r, 0, @step, @e)", cancellationToken, + ("id", row.Id), ("a", _account.AccountId), ("i", row.InstrumentId), ("s", row.Strategy), ("c", row.ClientOrderId), ("side", Wire.Text(row.Side)), ("k", Wire.Text(row.Kind)), + ("q", row.Quantity), ("l", row.Limit), ("st", row.Stop), ("now", row.CreatedAt), ("p", Wire.Text(row.Purpose)), ("tif", Wire.Text(row.TimeInForce)), ("po", row.PostOnly), + ("r", row.Reference), ("step", row.Step), ("e", row.ExecutionId)); + + private const string OrderSelect = + "SELECT id, execution_id, instrument_id, strategy, client_order_id, side, order_type, purpose, quantity, limit_price, stop_price, status, filled_quantity, " + + "average_fill_price, reference_price, step, time_in_force, post_only, created_at FROM orders"; + + private static OrderRow ReadOrder(DbRow r) => new( + r.Id("id"), r.IdOrNull("execution_id"), r.Id("instrument_id"), r.Text("strategy"), r.Text("client_order_id"), Wire.Side(r.Text("side")), Wire.Kind(r.Text("order_type")), + r.TextOrNull("purpose") is { } p ? Wire.Purpose(p) : OrderPurpose.Entry, r.Money("quantity"), r.MoneyOrNull("limit_price"), r.MoneyOrNull("stop_price"), + Wire.Status(r.Text("status")), r.MoneyOrNull("filled_quantity") ?? 0m, r.MoneyOrNull("average_fill_price"), r.MoneyOrNull("reference_price"), + r.IsNull("step") ? null : (int)r.Number("step"), r.TextOrNull("time_in_force") is { } t ? Wire.Tif(t) : TimeInForce.Day, + !r.IsNull("post_only") && r.Bool("post_only"), r.Moment("created_at")); + + public void Dispose() => _gate.Dispose(); + + private sealed record ExecRow(Guid Id, Guid InstrumentId, string Strategy, OrderSide Side, OrderPurpose Purpose, decimal Quantity, string Key, int Sequence, int Step, + decimal? Reference, decimal? Tolerance, decimal? StopLevel, DateTimeOffset StartedAt, DateTimeOffset? StepStartedAt, DateTimeOffset? AlertedAt); + + private sealed record OrderRow(Guid Id, Guid? ExecutionId, Guid InstrumentId, string Strategy, string ClientOrderId, OrderSide Side, OrderKind Kind, OrderPurpose Purpose, + decimal Quantity, decimal? Limit, decimal? Stop, OrderStatus Status, decimal Filled, decimal? AveragePrice, decimal? Reference, int? Step, TimeInForce TimeInForce, + bool PostOnly, DateTimeOffset CreatedAt); +} diff --git a/src/Anubis/Trading/OrderRules.cs b/src/Anubis/Trading/OrderRules.cs new file mode 100644 index 0000000..f2c491b --- /dev/null +++ b/src/Anubis/Trading/OrderRules.cs @@ -0,0 +1,290 @@ +using System.Security.Cryptography; +using System.Text; +using Anubis.Data; + +namespace Anubis.Trading; + +/// The parts of a client order id, read back without the database (SPEC 7.2, 15.1). +public sealed record ClientOrderIdParts(string Installation, string Environment, string Strategy, OrderPurpose Purpose, string Key, int Sequence); + +/// +/// Deterministic client order ids (SPEC 7.2): letters and digits only, 22 characters, under the 32 OKX allows. +/// ANU + installation (4) + environment (1) + strategy (2) + purpose (1) + decision or position (8) + +/// sequence (3). The sequence grows at every wanted send; only a resend after a network error reuses an id. +/// +public static class ClientOrderIds +{ + public const string Prefix = "ANU"; + public const int Length = 22; + + private const string Digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + + /// Two-letter codes of the strategies of SPEC 8. A strategy without a code cannot send orders. + public static readonly IReadOnlyDictionary StrategyCodes = new Dictionary + { + ["crypto_trend"] = "CT", + ["equity_momentum"] = "EM", + ["equity_meanrev"] = "MR", + + // Protective work that belongs to no strategy: "stop and close all", conformance runs. + ["system"] = "SY", + }; + + public static int MaxSequence { get; } = (36 * 36 * 36) - 1; + + /// Four characters that tell this installation's orders from another one's (trap 26). + public static string InstallationCode(Guid installationId) + { + var hash = SHA256.HashData(installationId.ToByteArray()); + return Base36(BitConverter.ToUInt64(hash, 0), 4); + } + + /// Eight characters for a decision or a position: the same id always gives the same key. + public static string Key(Guid id) + { + var hash = SHA256.HashData(id.ToByteArray()); + return Base36(BitConverter.ToUInt64(hash, 0), 8); + } + + public static string Build(string installation, string environment, string strategy, OrderPurpose purpose, string key, int sequence) + { + ArgumentNullException.ThrowIfNull(installation); + ArgumentNullException.ThrowIfNull(key); + if (installation.Length != 4 || !IsAlphanumeric(installation)) + { + throw new ArgumentException("The installation code has four letters or digits.", nameof(installation)); + } + + if (key.Length != 8 || !IsAlphanumeric(key)) + { + throw new ArgumentException("The key has eight letters or digits.", nameof(key)); + } + + if (!StrategyCodes.TryGetValue(strategy, out var code)) + { + throw new ArgumentException($"Strategy '{strategy}' has no order code.", nameof(strategy)); + } + + if (sequence < 0 || sequence > MaxSequence) + { + throw new ArgumentOutOfRangeException(nameof(sequence)); + } + + var id = new StringBuilder(Length) + .Append(Prefix) + .Append(installation.ToUpperInvariant()) + .Append(EnvironmentLetter(environment)) + .Append(code) + .Append(PurposeLetter(purpose)) + .Append(key.ToUpperInvariant()) + .Append(Base36((ulong)sequence, 3)) + .ToString(); + return id; + } + + /// The parts of an id Anubis made; null for any other order (the user's own, SPEC 7.1). + public static ClientOrderIdParts? Parse(string? id) + { + if (id is null || id.Length != Length || !id.StartsWith(Prefix, StringComparison.Ordinal) || !IsAlphanumeric(id)) + { + return null; + } + + var environment = id[7] switch + { + 'S' => TradingEnvironments.Simulation, + 'D' => TradingEnvironments.Demo, + 'L' => TradingEnvironments.Live, + _ => null, + }; + var strategy = StrategyCodes.FirstOrDefault(p => p.Value == id.Substring(8, 2)).Key; + OrderPurpose? purpose = id[10] switch + { + 'E' => OrderPurpose.Entry, + 'X' => OrderPurpose.Exit, + 'S' => OrderPurpose.Stop, + 'P' => OrderPurpose.Protective, + _ => null, + }; + if (environment is null || strategy is null || purpose is null) + { + return null; + } + + var sequence = 0; + foreach (var c in id[19..]) + { + sequence = (sequence * 36) + Digits.IndexOf(c, StringComparison.Ordinal); + } + + return new ClientOrderIdParts(id.Substring(3, 4), environment, strategy, purpose.Value, id.Substring(11, 8), sequence); + } + + /// True for an order Anubis made: the only ones it ever touches (SPEC 7.1). + public static bool IsOurs(string? id, string installation) => Parse(id) is { } parts && parts.Installation == installation; + + private static char EnvironmentLetter(string environment) => environment switch + { + TradingEnvironments.Simulation => 'S', + TradingEnvironments.Demo => 'D', + TradingEnvironments.Live => 'L', + _ => throw new ArgumentException("Unknown environment: " + environment, nameof(environment)), + }; + + private static char PurposeLetter(OrderPurpose purpose) => purpose switch + { + OrderPurpose.Entry => 'E', + OrderPurpose.Exit => 'X', + OrderPurpose.Stop => 'S', + OrderPurpose.Protective => 'P', + _ => throw new ArgumentOutOfRangeException(nameof(purpose)), + }; + + private static string Base36(ulong value, int width) + { + var chars = new char[width]; + for (var i = width - 1; i >= 0; i--) + { + chars[i] = Digits[(int)(value % 36)]; + value /= 36; + } + + return new string(chars); + } + + private static bool IsAlphanumeric(string text) => text.All(char.IsAsciiLetterOrDigit); +} + +/// Why an order was not sent: a code for the diary and the tests. +public static class OrderReasons +{ + public const string ZeroQuantity = "zero_quantity"; + public const string BelowMinimumSize = "below_min_size"; + public const string BelowMinimumNotional = "below_min_notional"; + public const string NoPrice = "no_price"; + public const string InstrumentClosed = "instrument_not_live"; + public const string PrudentMode = "account_prudent"; + public const string NotOurs = "not_ours"; +} + +/// An order after rounding, or the reason it cannot be sent. +public sealed record RoundedOrder(decimal Quantity, decimal? LimitPrice, decimal? StopPrice, string? Rejection) +{ + public bool IsValid => Rejection is null; +} + +/// +/// Rounding to tick and lot and the minimum check, before every send (SPEC 7.2, trap 4). Quantities round down, +/// never up: Anubis never buys more than decided nor sells more than it holds. Prices round on the cautious side. +/// +public static class OrderRules +{ + /// Alpaca accepts fractions to nine decimals and orders from 1 $ (SPEC 4.1). + public const decimal AlpacaFractionStep = 0.000000001m; + + public const decimal AlpacaMinimumNotional = 1m; + + public static decimal LotOf(InstrumentSpec spec) + { + ArgumentNullException.ThrowIfNull(spec); + if (spec.LotSize is > 0m) + { + return spec.LotSize.Value; + } + + return spec.Venue == Venues.Alpaca && spec.Fractionable != true ? 1m : AlpacaFractionStep; + } + + public static decimal MinimumNotionalOf(InstrumentSpec spec) + { + ArgumentNullException.ThrowIfNull(spec); + return spec.MinNotional ?? (spec.Venue == Venues.Alpaca ? AlpacaMinimumNotional : 0m); + } + + public static decimal RoundDown(decimal value, decimal step) => step <= 0m ? value : Math.Floor(value / step) * step; + + public static decimal RoundUp(decimal value, decimal step) => step <= 0m ? value : Math.Ceiling(value / step) * step; + + /// + /// A limit price on the tick: a buy rounds down and a sell rounds up, so the order never pays more than the + /// price asked (an aggressive limit never goes past its tolerance). + /// + public static decimal LimitPrice(decimal price, OrderSide side, decimal? tick) => + tick is > 0m ? (side == OrderSide.Buy ? RoundDown(price, tick.Value) : RoundUp(price, tick.Value)) : price; + + /// A sell stop rounds up: it triggers a little earlier, never later than its level. + public static decimal StopPrice(decimal price, decimal? tick) => tick is > 0m ? RoundUp(price, tick.Value) : price; + + /// The whole part of a quantity for Alpaca's GTC stop, and the fraction for the day stop (SPEC 7.2). + public static (decimal Whole, decimal Fraction) SplitWhole(decimal quantity) + { + var whole = Math.Floor(quantity); + return (whole, quantity - whole); + } + + /// Rounds an order and checks it against the instrument's minimums; the reference price values it. + public static RoundedOrder Round(InstrumentSpec spec, OrderSide side, OrderKind kind, decimal quantity, decimal referencePrice, decimal? limitPrice = null, decimal? stopPrice = null) + { + ArgumentNullException.ThrowIfNull(spec); + if (spec.Status is not (null or "live" or "active")) + { + return new(0m, null, null, OrderReasons.InstrumentClosed); + } + + var rounded = RoundDown(quantity, LotOf(spec)); + if (rounded <= 0m) + { + return new(0m, null, null, quantity <= 0m ? OrderReasons.ZeroQuantity : OrderReasons.BelowMinimumSize); + } + + if (spec.MinSize is > 0m && rounded < spec.MinSize.Value) + { + return new(rounded, null, null, OrderReasons.BelowMinimumSize); + } + + var limit = limitPrice is null ? (decimal?)null : LimitPrice(limitPrice.Value, side, spec.TickSize); + var stop = stopPrice is null ? (decimal?)null : StopPrice(stopPrice.Value, spec.TickSize); + var price = limit ?? stop ?? referencePrice; + if (price <= 0m) + { + return new(rounded, limit, stop, OrderReasons.NoPrice); + } + + // Stops protect what is held: a residue below the minimum value is still protected by the bot itself. + if (kind != OrderKind.Stop && rounded * price < MinimumNotionalOf(spec)) + { + return new(rounded, limit, stop, OrderReasons.BelowMinimumNotional); + } + + return new(rounded, limit, stop, null); + } + + /// True when a quantity cannot be sold on its own: below the lot, the minimum size or the minimum value. + public static bool IsUnsellable(InstrumentSpec spec, decimal quantity, decimal price) => + quantity > 0m && Round(spec, OrderSide.Sell, OrderKind.Limit, quantity, price).Rejection is OrderReasons.BelowMinimumSize or OrderReasons.BelowMinimumNotional; +} + +/// +/// The order state machine (SPEC 7.2). States only move forward; a final state never changes. A broker report +/// that skips states (an order filled before its acknowledgement arrived) is a forward move, so it is accepted. +/// +public static class OrderStates +{ + public static bool IsFinal(OrderStatus status) => status is OrderStatus.Filled or OrderStatus.Canceled or OrderStatus.Rejected or OrderStatus.Expired; + + public static bool CanMove(OrderStatus from, OrderStatus to) + { + if (IsFinal(from)) + { + return false; + } + + return to switch + { + OrderStatus.Created => false, + OrderStatus.Submitted => from == OrderStatus.Created, + OrderStatus.PartiallyFilled => from is OrderStatus.Created or OrderStatus.Submitted or OrderStatus.PartiallyFilled, + _ => true, + }; + } +} diff --git a/src/Anubis/Trading/Orders.cs b/src/Anubis/Trading/Orders.cs new file mode 100644 index 0000000..709b552 --- /dev/null +++ b/src/Anubis/Trading/Orders.cs @@ -0,0 +1,326 @@ +using System.Globalization; + +namespace Anubis.Trading; + +/// The three environments of SPEC 7.1. The value is stored in accounts.environment. +public static class TradingEnvironments +{ + /// The internal simulator (SPEC 7.3): always available, no broker behind it. + public const string Simulation = "simulation"; + + /// A broker's practice account: Alpaca paper, OKX demo. + public const string Demo = "demo"; + + /// Real money. Adapters accept it only with the startup consent (SPEC 2.2). + public const string Live = "live"; + + public static bool IsKnown(string? value) => value is Simulation or Demo or Live; + + /// Simulated money and real money are shown and counted apart (SPEC 7.1). + public static string World(string environment) => environment == Live ? "real" : "simulated"; +} + +public enum OrderSide +{ + Buy, + Sell, +} + +/// Order types Anubis uses. Stops are always stop-market: they must fill (SPEC 7.2). +public enum OrderKind +{ + Limit, + Market, + Stop, +} + +public enum TimeInForce +{ + Day, + Gtc, + Ioc, +} + +/// Why an order exists: it is part of the client order id (SPEC 7.2). +public enum OrderPurpose +{ + /// Opens or increases a position on a strategy's decision. + Entry, + + /// Reduces or closes a position on a strategy's decision. + Exit, + + /// A protective stop resting on the broker. + Stop, + + /// A protective market sale: stop already passed, half-triggered stop pair, "stop and close all". + Protective, +} + +/// The order state machine of SPEC 7.2. +public enum OrderStatus +{ + Created, + Submitted, + PartiallyFilled, + Filled, + Canceled, + Rejected, + Expired, +} + +/// Text forms stored in the database and read from the brokers. +public static class Wire +{ + public static string Text(OrderStatus status) => status switch + { + OrderStatus.Created => "created", + OrderStatus.Submitted => "submitted", + OrderStatus.PartiallyFilled => "partially_filled", + OrderStatus.Filled => "filled", + OrderStatus.Canceled => "canceled", + OrderStatus.Rejected => "rejected", + OrderStatus.Expired => "expired", + _ => throw new ArgumentOutOfRangeException(nameof(status)), + }; + + public static OrderStatus Status(string text) => text switch + { + "created" => OrderStatus.Created, + "submitted" => OrderStatus.Submitted, + "partially_filled" => OrderStatus.PartiallyFilled, + "filled" => OrderStatus.Filled, + "canceled" => OrderStatus.Canceled, + "rejected" => OrderStatus.Rejected, + "expired" => OrderStatus.Expired, + _ => throw new FormatException("Unknown order status: " + text), + }; + + public static string Text(OrderSide side) => side == OrderSide.Buy ? "buy" : "sell"; + + public static OrderSide Side(string text) => text switch + { + "buy" => OrderSide.Buy, + "sell" => OrderSide.Sell, + _ => throw new FormatException("Unknown order side: " + text), + }; + + public static string Text(OrderKind kind) => kind.ToString().ToLowerInvariant(); + + public static OrderKind Kind(string text) => Enum.Parse(text, ignoreCase: true); + + public static string Text(TimeInForce tif) => tif.ToString().ToLowerInvariant(); + + public static TimeInForce Tif(string text) => Enum.Parse(text, ignoreCase: true); + + public static string Text(OrderPurpose purpose) => purpose.ToString().ToLowerInvariant(); + + public static OrderPurpose Purpose(string text) => Enum.Parse(text, ignoreCase: true); + + public static string Number(decimal value) => Db.DbValues.Normalize(value).ToString(CultureInfo.InvariantCulture); +} + +/// What the order manager asks a broker to do. Quantities and prices are already rounded (SPEC 7.2). +public sealed record OrderRequest( + string ClientOrderId, + string Symbol, + OrderSide Side, + OrderKind Kind, + decimal Quantity, + TimeInForce TimeInForce) +{ + public decimal? LimitPrice { get; init; } + + public decimal? StopPrice { get; init; } + + /// OKX: the order only rests on the book and pays the maker fee (the first chase steps). + public bool PostOnly { get; init; } +} + +/// An order as the broker sees it. +public sealed record BrokerOrder( + string ClientOrderId, + string? BrokerOrderId, + string Symbol, + OrderSide Side, + OrderKind Kind, + decimal Quantity, + OrderStatus Status, + decimal FilledQuantity, + DateTimeOffset UpdatedAt) +{ + public decimal? LimitPrice { get; init; } + + public decimal? StopPrice { get; init; } + + public TimeInForce TimeInForce { get; init; } = TimeInForce.Day; + + public decimal? AverageFillPrice { get; init; } + + /// The broker's reason for a rejection or a cancellation, in its own words. + public string? Reason { get; init; } + + public decimal Remaining => Math.Max(0m, Quantity - FilledQuantity); + + public bool IsOpen => Status is OrderStatus.Created or OrderStatus.Submitted or OrderStatus.PartiallyFilled; +} + +/// +/// One execution. is the broker's own id, so the same execution from the stream and +/// from the fallback query is recorded once. The fee may be in kind: in the base currency of a crypto purchase. +/// +public sealed record BrokerFill( + string ExecutionId, + string ClientOrderId, + string Symbol, + OrderSide Side, + decimal Quantity, + decimal Price, + decimal Fee, + string FeeCurrency, + DateTimeOffset ExecutedAt); + +/// Balances of an account, by currency, as the broker reports them. +public sealed record AccountSnapshot(string Currency, decimal Equity, IReadOnlyDictionary Cash, DateTimeOffset At) +{ + /// What the broker says can be spent now (unsettled proceeds excluded where it says so: SPEC 4.1). + public decimal? BuyingPower { get; init; } +} + +public sealed record BrokerPosition(string Symbol, decimal Quantity, decimal? AveragePrice); + +/// Cash movements read from a broker: for reconciliation and dividends, never for the return (SPEC 7.5). +public sealed record CashActivity(string Id, string Kind, decimal Amount, string Currency, DateTimeOffset At) +{ + public string? Symbol { get; init; } +} + +public static class CashActivityKinds +{ + public const string Deposit = "deposit"; + public const string Withdrawal = "withdrawal"; + public const string Dividend = "dividend"; + public const string Fee = "fee"; + public const string Other = "other"; +} + +/// What a key may do. A key that can withdraw is never used (SPEC 2.2). +public sealed record KeyPermissions(bool CanRead, bool CanTrade, bool CanWithdraw, string Description); + +/// What a venue supports and how its stops must be shaped (SPEC 4.1, 4.2, 7.2). +public sealed record BrokerCapabilities +{ + public bool Fractional { get; init; } + + /// Fractional quantities accept only day orders: their stops expire every evening (Alpaca). + public bool FractionalStopsAreDayOnly { get; init; } + + /// A buy is refused while a sell stop rests on the same symbol (Alpaca 403, SPEC 4.1). + public bool OppositeSideBlocked { get; init; } + + public bool PostOnly { get; init; } + + /// Purchase fees are taken from the bought coin (OKX spot). + public bool FeeInKind { get; init; } + + public bool StopsAreTriggerOrders { get; init; } +} + +/// A change of an order, with the execution that caused it when there is one. +public sealed record OrderUpdate(BrokerOrder Order, BrokerFill? Fill); + +/// +/// The account side of SPEC 5.3 BrokerAdapter: account, positions, orders, fills, cash movements. Market +/// data stays on , as in Phase 2. Every implementation is built through +/// , which refuses a real account without the startup consent. +/// +public interface IBrokerAccount +{ + string Venue { get; } + + /// One of . + string Environment { get; } + + BrokerCapabilities Capabilities { get; } + + Task ServerTimeAsync(CancellationToken cancellationToken); + + Task GetAccountAsync(CancellationToken cancellationToken); + + Task> GetPositionsAsync(CancellationToken cancellationToken); + + Task> GetOpenOrdersAsync(CancellationToken cancellationToken); + + /// + /// Sends an order. Idempotent on the client order id: if the broker already has it, the existing order comes + /// back and nothing new is created. A refusal throws . + /// + Task SubmitOrderAsync(OrderRequest request, CancellationToken cancellationToken); + + /// Asks to cancel. The answer is the order afterwards, when the broker gives it. + Task CancelOrderAsync(string clientOrderId, string symbol, CancellationToken cancellationToken); + + /// The order with this client id, or null when the broker never received it. + Task GetOrderAsync(string clientOrderId, string symbol, CancellationToken cancellationToken); + + Task> GetFillsAsync(DateTimeOffset since, CancellationToken cancellationToken); + + Task> GetCashActivitiesAsync(DateTimeOffset since, CancellationToken cancellationToken); + + Task GetKeyPermissionsAsync(CancellationToken cancellationToken); + + /// Order changes as they happen. Ends when the connection drops; the caller reconnects and queries. + IAsyncEnumerable StreamOrderUpdatesAsync(CancellationToken cancellationToken); +} + +/// A broker call failed. : the network or the broker, not the request. +public class BrokerException : Exception +{ + public BrokerException() + { + } + + public BrokerException(string message) + : base(message) + { + } + + public BrokerException(string message, Exception inner) + : base(message, inner) + { + } + + public BrokerException(string message, bool retryable, Exception? inner = null) + : base(message, inner) + { + Retryable = retryable; + } + + public bool Retryable { get; } +} + +/// The broker refused the order: it does not exist on the broker and will not be resent as it is. +public sealed class OrderRejectedException : BrokerException +{ + public OrderRejectedException() + { + } + + public OrderRejectedException(string message) + : base(message) + { + } + + public OrderRejectedException(string message, Exception inner) + : base(message, inner) + { + } + + public OrderRejectedException(string message, string code) + : base(message, retryable: false) + { + Code = code; + } + + public string Code { get; } = "rejected"; +} diff --git a/src/Anubis/Trading/PaperBroker.cs b/src/Anubis/Trading/PaperBroker.cs new file mode 100644 index 0000000..317e4c1 --- /dev/null +++ b/src/Anubis/Trading/PaperBroker.cs @@ -0,0 +1,825 @@ +using System.Globalization; +using System.Runtime.CompilerServices; +using System.Text.Json; +using System.Threading.Channels; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; + +namespace Anubis.Trading; + +/// Fees and behaviour the simulator copies from a venue's price list (SPEC 4.1, 4.2, 7.3). +public sealed record PaperOptions +{ + public required string Venue { get; init; } + + public required string Currency { get; init; } + + public decimal MakerFee { get; init; } + + public decimal TakerFee { get; init; } + + /// OKX keeps the purchase fee in the bought coin. + public bool FeeInKind { get; init; } + + /// US regulatory fee on the value of sales (SEC Section 31), rounded up to the cent (API-NOTES). + public decimal SellValueFee { get; init; } + + /// Per-share fee on buys and sells (FINRA CAT), rounded up to the cent (API-NOTES). + public decimal ShareFee { get; init; } + + public TimeSpan MinLatency { get; init; } = TimeSpan.FromMilliseconds(300); + + public TimeSpan MaxLatency { get; init; } = TimeSpan.FromMilliseconds(1000); + + /// A quote older than this is not used to fill: the simulator waits for a fresh one. + public TimeSpan QuoteMaxAge { get; init; } = TimeSpan.FromSeconds(60); + + public ulong Seed { get; init; } = 20261110; + + /// OKX Europe spot, accounts without derivatives: 0,10% maker, 0,20% taker (SPEC 4.2). + public static PaperOptions Okx(string currency = "EUR") => new() + { + Venue = Venues.Okx, + Currency = currency, + MakerFee = 0.001m, + TakerFee = 0.002m, + FeeInKind = true, + }; + + /// + /// Alpaca: no commission; SEC fee on the value of sales and FINRA CAT fee per share, from the price list of + /// 12/10/2026 (API-NOTES). Alpaca sums them by day; here each fill rounds up on its own, slightly more prudent. + /// + public static PaperOptions Alpaca() => new() + { + Venue = Venues.Alpaca, + Currency = "USD", + SellValueFee = 0.0000206m, + ShareFee = 0.000003m, + }; + + public bool StopsReserveQuantity => Venue == Venues.Alpaca; +} + +/// What the simulator holds: its whole state, saved as one JSON document after every change. +public sealed class PaperBook +{ + public Dictionary Cash { get; set; } = []; + + public Dictionary Holdings { get; set; } = []; + + public List Orders { get; set; } = []; + + public List Fills { get; set; } = []; + + public List Activities { get; set; } = []; + + public long Sequence { get; set; } + + /// Until when the simulator saw prices: after an absence it replays the minutes from here (SPEC 7.3). + public DateTimeOffset SeenUntil { get; set; } +} + +public sealed class PaperHolding +{ + public decimal Quantity { get; set; } + + public decimal AveragePrice { get; set; } +} + +public sealed class PaperOrder +{ + public required OrderRequest Request { get; set; } + + public required string BrokerOrderId { get; set; } + + public OrderStatus Status { get; set; } + + public decimal Filled { get; set; } + + public decimal FilledValue { get; set; } + + public DateTimeOffset SubmittedAt { get; set; } + + /// The order reaches the simulated market only after its latency (SPEC 7.3). + public DateTimeOffset ActiveAt { get; set; } + + /// The order was not marketable on arrival: it rests on the book and pays the maker fee. + public bool Resting { get; set; } + + public bool Evaluated { get; set; } + + public string? Reason { get; set; } + + public DateTimeOffset UpdatedAt { get; set; } +} + +/// Where the simulator keeps its book between starts. +public interface IPaperBookStore +{ + Task LoadAsync(CancellationToken cancellationToken); + + Task SaveAsync(PaperBook book, CancellationToken cancellationToken); +} + +/// The book of a simulator account in simulator_books. +public sealed class PaperBookStore(Database db, IClock clock, Guid accountId) : IPaperBookStore +{ + private static readonly JsonSerializerOptions _json = new() { WriteIndented = false }; + + public async Task LoadAsync(CancellationToken cancellationToken) + { + var text = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT book FROM simulator_books WHERE account_id = @a", r => r.Json("book").Text, ("a", accountId)), cancellationToken) + .ConfigureAwait(false); + return text is null ? null : JsonSerializer.Deserialize(text, _json); + } + + public Task SaveAsync(PaperBook book, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(book); + var json = new DbJson(JsonSerializer.Serialize(book, _json)); + var now = clock.UtcNow; + return db.WriteAsync(async s => + { + var changed = await s.ExecuteAsync("UPDATE simulator_books SET book = @b, seen_until = @u, updated_at = @now WHERE account_id = @a", cancellationToken, + ("b", json), ("u", book.SeenUntil), ("now", now), ("a", accountId)).ConfigureAwait(false); + if (changed == 0) + { + await s.ExecuteAsync("INSERT INTO simulator_books (id, account_id, book, seen_until, created_at, updated_at) VALUES (@id, @a, @b, @u, @now, @now)", cancellationToken, + ("id", Ids.NewId(clock)), ("a", accountId), ("b", json), ("u", book.SeenUntil), ("now", now)).ConfigureAwait(false); + } + }, cancellationToken); + } +} + +/// +/// The internal simulator (SPEC 5.3, 7.3): a broker that fills against live quotes, prudently. Bid and ask plus a +/// slippage by liquidity tier; a limit fills only when the price crosses it; 300–1,000 ms of latency; fees of the +/// venue's price list, in kind where the venue does so; dividends from the corporate actions; after an absence, +/// the one-minute bars of the gap are replayed for stops and sales, and waiting purchases are cancelled. The same +/// rounding and minimums as the real venue. Deterministic: latency comes from a fixed seed, time from the clock. +/// +public sealed class PaperBroker : IBrokerAccount, IDisposable +{ + private readonly PaperOptions _options; + private readonly IClock _clock; + private readonly Func> _quotes; + private readonly Func _instruments; + private readonly IPaperBookStore? _store; + private readonly SemaphoreSlim _gate = new(1, 1); + private readonly Channel _updates = Channel.CreateUnbounded(); + private PaperBook _book = new(); + private bool _loaded; + + public PaperBroker(PaperOptions options, IClock clock, Func> quotes, Func instruments, IPaperBookStore? store = null) + { + _options = options ?? throw new ArgumentNullException(nameof(options)); + _clock = clock ?? throw new ArgumentNullException(nameof(clock)); + _quotes = quotes ?? throw new ArgumentNullException(nameof(quotes)); + _instruments = instruments ?? throw new ArgumentNullException(nameof(instruments)); + _store = store; + Capabilities = new BrokerCapabilities + { + Fractional = options.Venue == Venues.Alpaca || options.Venue == Venues.Okx, + FractionalStopsAreDayOnly = options.Venue == Venues.Alpaca, + OppositeSideBlocked = options.Venue == Venues.Alpaca, + PostOnly = options.Venue == Venues.Okx, + FeeInKind = options.FeeInKind, + StopsAreTriggerOrders = options.Venue == Venues.Okx, + }; + } + + public string Venue => _options.Venue; + + public string Environment => TradingEnvironments.Simulation; + + public BrokerCapabilities Capabilities { get; } + + public PaperOptions Options => _options; + + /// Slippage by liquidity tier (SPEC 7.3): 5 bp for stocks and BTC, ETH, SOL; 15 bp for other coins. + public static decimal SlippageBp(InstrumentSpec? spec) + { + if (spec is null || spec.AssetClass == AssetClasses.Equity) + { + return 5m; + } + + var coin = spec.BaseCurrency ?? spec.Symbol.Split('-', '/')[0]; + return coin is "BTC" or "ETH" or "SOL" ? 5m : 15m; + } + + /// Puts money on the simulated account: the bot's capital lives in its ledger, this is only the balance. + public async Task DepositAsync(decimal amount, string? currency, CancellationToken cancellationToken) + { + await WithBookAsync(book => + { + var ccy = currency ?? _options.Currency; + book.Cash[ccy] = book.Cash.GetValueOrDefault(ccy) + amount; + book.Activities.Add(new CashActivity(NextId(book, "D"), amount >= 0m ? CashActivityKinds.Deposit : CashActivityKinds.Withdrawal, amount, ccy, _clock.UtcNow)); + return true; + }, cancellationToken).ConfigureAwait(false); + } + + /// Credits a cash dividend on the quantity held (SPEC 7.3), from the corporate actions. + public async Task PayDividendAsync(string symbol, decimal perShare, string currency, DateTimeOffset at, CancellationToken cancellationToken) + { + decimal paid = 0m; + await WithBookAsync(book => + { + var held = book.Holdings.GetValueOrDefault(symbol)?.Quantity ?? 0m; + paid = DbValues.Money(held * perShare); + if (paid <= 0m) + { + return false; + } + + book.Cash[currency] = book.Cash.GetValueOrDefault(currency) + paid; + book.Activities.Add(new CashActivity(NextId(book, "V"), CashActivityKinds.Dividend, paid, currency, at) { Symbol = symbol }); + return true; + }, cancellationToken).ConfigureAwait(false); + return paid; + } + + /// Applies a split to the simulated holding and to resting orders: quantities times the ratio, prices divided. + public async Task ApplySplitAsync(string symbol, decimal ratio, CancellationToken cancellationToken) + { + await WithBookAsync(book => + { + if (book.Holdings.TryGetValue(symbol, out var holding)) + { + holding.Quantity *= ratio; + holding.AveragePrice = DbValues.Money(holding.AveragePrice / ratio); + } + + foreach (var order in book.Orders.Where(o => o.Request.Symbol == symbol && IsOpen(o))) + { + order.Request = order.Request with + { + Quantity = order.Request.Quantity * ratio, + LimitPrice = order.Request.LimitPrice / ratio, + StopPrice = order.Request.StopPrice / ratio, + }; + order.Filled *= ratio; + } + + return true; + }, cancellationToken).ConfigureAwait(false); + } + + public Task ServerTimeAsync(CancellationToken cancellationToken) => Task.FromResult(_clock.UtcNow); + + public async Task GetAccountAsync(CancellationToken cancellationToken) + { + await PumpAsync(cancellationToken).ConfigureAwait(false); + var book = await SnapshotAsync(cancellationToken).ConfigureAwait(false); + var invested = 0m; + foreach (var (symbol, holding) in book.Holdings) + { + var quote = await _quotes(symbol, cancellationToken).ConfigureAwait(false); + invested += holding.Quantity * (quote?.Bid ?? holding.AveragePrice); + } + + var cash = book.Cash.GetValueOrDefault(_options.Currency); + return new AccountSnapshot(_options.Currency, DbValues.Money(cash + invested), new Dictionary(book.Cash), _clock.UtcNow) { BuyingPower = cash }; + } + + public async Task> GetPositionsAsync(CancellationToken cancellationToken) + { + await PumpAsync(cancellationToken).ConfigureAwait(false); + var book = await SnapshotAsync(cancellationToken).ConfigureAwait(false); + return book.Holdings.Where(h => h.Value.Quantity > 0m).Select(h => new BrokerPosition(h.Key, h.Value.Quantity, h.Value.AveragePrice)).ToList(); + } + + public async Task> GetOpenOrdersAsync(CancellationToken cancellationToken) + { + await PumpAsync(cancellationToken).ConfigureAwait(false); + var book = await SnapshotAsync(cancellationToken).ConfigureAwait(false); + return book.Orders.Where(IsOpen).Select(ToBroker).ToList(); + } + + public async Task SubmitOrderAsync(OrderRequest request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + BrokerOrder? result = null; + string? rejection = null; + await WithBookAsync(book => + { + var existing = book.Orders.FirstOrDefault(o => o.Request.ClientOrderId == request.ClientOrderId); + if (existing is not null) + { + result = ToBroker(existing); + return false; + } + + rejection = Validate(book, request); + if (rejection is not null) + { + return false; + } + + var now = _clock.UtcNow; + var order = new PaperOrder + { + Request = request, + BrokerOrderId = NextId(book, "O"), + Status = OrderStatus.Submitted, + SubmittedAt = now, + ActiveAt = now + Latency(book.Sequence), + UpdatedAt = now, + }; + book.Orders.Add(order); + result = ToBroker(order); + Publish(order, null); + return true; + }, cancellationToken).ConfigureAwait(false); + return rejection is not null + ? throw new OrderRejectedException($"Simulatore: ordine {request.ClientOrderId} rifiutato ({rejection}).", rejection) + : result!; + } + + public async Task CancelOrderAsync(string clientOrderId, string symbol, CancellationToken cancellationToken) + { + await PumpAsync(cancellationToken).ConfigureAwait(false); + await WithBookAsync(book => + { + var order = book.Orders.FirstOrDefault(o => o.Request.ClientOrderId == clientOrderId); + if (order is null || !IsOpen(order)) + { + return false; + } + + Finish(order, OrderStatus.Canceled, "canceled"); + return true; + }, cancellationToken).ConfigureAwait(false); + } + + public async Task GetOrderAsync(string clientOrderId, string symbol, CancellationToken cancellationToken) + { + await PumpAsync(cancellationToken).ConfigureAwait(false); + var book = await SnapshotAsync(cancellationToken).ConfigureAwait(false); + var order = book.Orders.FirstOrDefault(o => o.Request.ClientOrderId == clientOrderId); + return order is null ? null : ToBroker(order); + } + + public async Task> GetFillsAsync(DateTimeOffset since, CancellationToken cancellationToken) + { + await PumpAsync(cancellationToken).ConfigureAwait(false); + var book = await SnapshotAsync(cancellationToken).ConfigureAwait(false); + return book.Fills.Where(f => f.ExecutedAt >= since).ToList(); + } + + public async Task> GetCashActivitiesAsync(DateTimeOffset since, CancellationToken cancellationToken) + { + var book = await SnapshotAsync(cancellationToken).ConfigureAwait(false); + return book.Activities.Where(a => a.At >= since).ToList(); + } + + public Task GetKeyPermissionsAsync(CancellationToken cancellationToken) => + Task.FromResult(new KeyPermissions(true, true, false, "Simulatore interno: nessuna chiave.")); + + public async IAsyncEnumerable StreamOrderUpdatesAsync([EnumeratorCancellation] CancellationToken cancellationToken) + { + while (await _updates.Reader.WaitToReadAsync(cancellationToken).ConfigureAwait(false)) + { + while (_updates.Reader.TryRead(out var update)) + { + yield return update; + } + } + } + + /// Day orders end at the close of the session (stocks), as on the broker. + public async Task ExpireDayOrdersAsync(CancellationToken cancellationToken) + { + await WithBookAsync(book => + { + var any = false; + foreach (var order in book.Orders.Where(o => IsOpen(o) && o.Request.TimeInForce == TimeInForce.Day)) + { + Finish(order, OrderStatus.Expired, "day_order_expired"); + any = true; + } + + return any; + }, cancellationToken).ConfigureAwait(false); + } + + /// + /// Matches the active orders against the current quotes. Called by every read, so an order is filled as soon as + /// anyone looks after its latency has passed and the price has crossed it. + /// + public async Task PumpAsync(CancellationToken cancellationToken) + { + var book = await SnapshotAsync(cancellationToken).ConfigureAwait(false); + var symbols = book.Orders.Where(IsOpen).Select(o => o.Request.Symbol).Distinct(StringComparer.Ordinal).ToList(); + var quotes = new Dictionary(StringComparer.Ordinal); + foreach (var symbol in symbols) + { + if (await _quotes(symbol, cancellationToken).ConfigureAwait(false) is { } quote && _clock.UtcNow - quote.At <= _options.QuoteMaxAge && quote.Bid > 0m && quote.Ask >= quote.Bid) + { + quotes[symbol] = quote; + } + } + + await WithBookAsync(b => + { + var now = _clock.UtcNow; + var changed = false; + foreach (var order in b.Orders.Where(o => IsOpen(o) && o.ActiveAt <= now).ToList()) + { + if (quotes.TryGetValue(order.Request.Symbol, out var quote)) + { + changed |= Match(b, order, quote); + } + } + + if (quotes.Count > 0 || symbols.Count == 0) + { + b.SeenUntil = now; + changed = true; + } + + return changed; + }, cancellationToken).ConfigureAwait(false); + } + + /// + /// After an absence (SPEC 7.3): waiting purchases are cancelled; stops and sales that would have triggered are + /// filled at their level, or at the open of the bar that already passed it. Bars come from the one-minute store. + /// + public async Task CatchUpAsync(Func>> minuteBars, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(minuteBars); + var book = await SnapshotAsync(cancellationToken).ConfigureAwait(false); + var from = book.SeenUntil; + var until = _clock.UtcNow; + var bars = new Dictionary>(StringComparer.Ordinal); + foreach (var symbol in book.Orders.Where(o => IsOpen(o) && o.Request.Side == OrderSide.Sell).Select(o => o.Request.Symbol).Distinct(StringComparer.Ordinal)) + { + bars[symbol] = (await minuteBars(symbol, from, until, cancellationToken).ConfigureAwait(false)).OrderBy(b => b.OpensAt).ToList(); + } + + var handled = 0; + await WithBookAsync(b => + { + foreach (var order in b.Orders.Where(IsOpen).ToList()) + { + if (order.Request.Side == OrderSide.Buy) + { + Finish(order, OrderStatus.Canceled, "canceled_after_absence"); + handled++; + continue; + } + + foreach (var bar in bars.GetValueOrDefault(order.Request.Symbol) ?? []) + { + if (bar.OpensAt < from || bar.OpensAt < order.ActiveAt.AddMinutes(-1)) + { + continue; + } + + var open = (decimal)bar.Open; + var high = (decimal)bar.High; + var low = (decimal)bar.Low; + var slip = SlippageBp(_instruments(order.Request.Symbol)) / 10_000m; + decimal? price = order.Request.Kind switch + { + OrderKind.Market => open * (1m - slip), + OrderKind.Stop when low <= order.Request.StopPrice => Math.Min(open, order.Request.StopPrice!.Value) * (1m - slip), + OrderKind.Limit when high > order.Request.LimitPrice => Math.Max(open, order.Request.LimitPrice!.Value), + _ => null, + }; + if (price is null) + { + continue; + } + + var at = bar.OpensAt.AddSeconds(30) < until ? bar.OpensAt.AddSeconds(30) : until; + Execute(b, order, order.Request.Quantity - order.Filled, RoundAdverse(order, price.Value), taker: order.Request.Kind != OrderKind.Limit, at); + handled++; + break; + } + } + + b.SeenUntil = until; + return true; + }, cancellationToken).ConfigureAwait(false); + return handled; + } + + private bool Match(PaperBook book, PaperOrder order, Quote quote) + { + var request = order.Request; + var spec = _instruments(request.Symbol); + var slip = SlippageBp(spec) / 10_000m; + var remaining = request.Quantity - order.Filled; + var firstLook = !order.Evaluated; + order.Evaluated = true; + switch (request.Kind) + { + case OrderKind.Market: + { + var price = request.Side == OrderSide.Buy ? quote.Ask * (1m + slip) : quote.Bid * (1m - slip); + return Execute(book, order, Available(quote, request.Side, remaining), RoundAdverse(order, price), taker: true, _clock.UtcNow); + } + + case OrderKind.Stop: + { + if (request.Side != OrderSide.Sell || quote.Bid > request.StopPrice) + { + return false; + } + + var price = Math.Min(request.StopPrice!.Value, quote.Bid) * (1m - slip); + return Execute(book, order, remaining, RoundAdverse(order, price), taker: true, _clock.UtcNow); + } + + default: + { + var limit = request.LimitPrice!.Value; + var crosses = request.Side == OrderSide.Buy ? quote.Ask < limit : quote.Bid > limit; + if (firstLook && crosses) + { + if (request.PostOnly) + { + Finish(order, OrderStatus.Canceled, "post_only_would_take"); + return true; + } + + // Marketable on arrival: it takes liquidity, with the slippage, never past its limit. + var price = request.Side == OrderSide.Buy ? Math.Min(limit, quote.Ask * (1m + slip)) : Math.Max(limit, quote.Bid * (1m - slip)); + return Execute(book, order, Available(quote, request.Side, remaining), RoundAdverse(order, price), taker: true, _clock.UtcNow); + } + + if (firstLook) + { + order.Resting = true; + return true; + } + + // Resting: filled at its own price only when the market trades through it. + return crosses && Execute(book, order, Available(quote, request.Side, remaining), limit, taker: false, _clock.UtcNow); + } + } + } + + private static decimal Available(Quote quote, OrderSide side, decimal remaining) + { + var size = side == OrderSide.Buy ? quote.AskSize : quote.BidSize; + return size is > 0m ? Math.Min(remaining, size.Value) : remaining; + } + + private bool Execute(PaperBook book, PaperOrder order, decimal quantity, decimal price, bool taker, DateTimeOffset at) + { + var request = order.Request; + var spec = _instruments(request.Symbol); + quantity = OrderRules.RoundDown(quantity, spec is null ? 0m : OrderRules.LotOf(spec)); + if (quantity <= 0m || price <= 0m) + { + return false; + } + + var gross = DbValues.Money(quantity * price); + var currency = spec?.QuoteCurrency ?? _options.Currency; + var coin = spec?.BaseCurrency ?? request.Symbol.Split('-', '/')[0]; + var rate = taker ? _options.TakerFee : _options.MakerFee; + decimal fee; + string feeCurrency; + var holding = book.Holdings.TryGetValue(request.Symbol, out var h) ? h : book.Holdings[request.Symbol] = new PaperHolding(); + if (request.Side == OrderSide.Buy) + { + if (book.Cash.GetValueOrDefault(currency) < gross) + { + Finish(order, order.Filled > 0m ? OrderStatus.Canceled : OrderStatus.Rejected, "insufficient_funds"); + return true; + } + + if (_options.FeeInKind) + { + fee = DbValues.Money(quantity * rate); + feeCurrency = coin; + } + else + { + fee = DbValues.Money(gross * rate) + (_options.ShareFee > 0m ? OrderRules.RoundUp(quantity * _options.ShareFee, 0.01m) : 0m); + feeCurrency = currency; + } + + var received = quantity - (feeCurrency == coin ? fee : 0m); + holding.AveragePrice = DbValues.Money(((holding.Quantity * holding.AveragePrice) + gross) / (holding.Quantity + received)); + holding.Quantity += received; + book.Cash[currency] = book.Cash.GetValueOrDefault(currency) - gross - (feeCurrency == currency ? fee : 0m); + } + else + { + quantity = Math.Min(quantity, holding.Quantity); + if (quantity <= 0m) + { + Finish(order, OrderStatus.Rejected, "insufficient_quantity"); + return true; + } + + gross = DbValues.Money(quantity * price); + fee = DbValues.Money(gross * rate); + if (_options.SellValueFee > 0m || _options.ShareFee > 0m) + { + fee += OrderRules.RoundUp(gross * _options.SellValueFee, 0.01m) + OrderRules.RoundUp(quantity * _options.ShareFee, 0.01m); + } + + feeCurrency = currency; + holding.Quantity -= quantity; + book.Cash[currency] = book.Cash.GetValueOrDefault(currency) + gross - fee; + if (holding.Quantity <= 0m) + { + book.Holdings.Remove(request.Symbol); + } + } + + order.Filled += quantity; + order.FilledValue += gross; + var fill = new BrokerFill(NextId(book, "F"), request.ClientOrderId, request.Symbol, request.Side, quantity, price, fee, feeCurrency, at); + book.Fills.Add(fill); + order.Status = order.Filled >= request.Quantity ? OrderStatus.Filled : OrderStatus.PartiallyFilled; + order.UpdatedAt = at; + Publish(order, fill); + return true; + } + + private string? Validate(PaperBook book, OrderRequest request) + { + var spec = _instruments(request.Symbol); + if (spec is null) + { + return "unknown_instrument"; + } + + if (request.Quantity <= 0m) + { + return OrderReasons.ZeroQuantity; + } + + var lot = OrderRules.LotOf(spec); + if (OrderRules.RoundDown(request.Quantity, lot) != request.Quantity) + { + return "quantity_not_on_lot"; + } + + if (spec.MinSize is > 0m && request.Quantity < spec.MinSize.Value) + { + return OrderReasons.BelowMinimumSize; + } + + var price = request.LimitPrice ?? request.StopPrice; + if (request.Kind == OrderKind.Limit && price is null) + { + return OrderReasons.NoPrice; + } + + if (request.Kind == OrderKind.Stop && (request.StopPrice is null || request.Side != OrderSide.Sell)) + { + return "stop_must_be_sell"; + } + + if (spec.TickSize is > 0m && price is { } p && OrderRules.RoundDown(p, spec.TickSize.Value) != p) + { + return "price_not_on_tick"; + } + + if (_options.Venue == Venues.Alpaca && request.Quantity != decimal.Truncate(request.Quantity) && request.TimeInForce != TimeInForce.Day) + { + return "fractional_orders_must_be_day"; + } + + var open = book.Orders.Where(o => IsOpen(o) && o.Request.Symbol == request.Symbol).ToList(); + if (Capabilities.OppositeSideBlocked && open.Any(o => o.Request.Side != request.Side && WouldWashTrade(o.Request, request))) + { + // Alpaca refuses an order with an opposite open order on the same symbol; two limits only when the buy + // is at or above the sell (SPEC 4.1, API-NOTES). + return "opposite_side_order_open"; + } + + if (request.Side == OrderSide.Sell) + { + var reserved = open.Where(o => o.Request.Side == OrderSide.Sell && (o.Request.Kind != OrderKind.Stop || _options.StopsReserveQuantity)) + .Sum(o => o.Request.Quantity - o.Filled); + var held = book.Holdings.GetValueOrDefault(request.Symbol)?.Quantity ?? 0m; + if (request.Quantity + (request.Kind != OrderKind.Stop || _options.StopsReserveQuantity ? reserved : 0m) > held) + { + return "insufficient_quantity"; + } + } + else if (request.Kind == OrderKind.Limit) + { + var currency = spec.QuoteCurrency; + if (request.Quantity * request.LimitPrice!.Value > book.Cash.GetValueOrDefault(currency)) + { + return "insufficient_funds"; + } + } + + if (request.Kind != OrderKind.Stop && price is { } value && request.Quantity * value < OrderRules.MinimumNotionalOf(spec)) + { + return OrderReasons.BelowMinimumNotional; + } + + return null; + } + + private static bool WouldWashTrade(OrderRequest open, OrderRequest incoming) + { + if (open.Kind != OrderKind.Limit || incoming.Kind != OrderKind.Limit) + { + return true; + } + + var (buy, sell) = incoming.Side == OrderSide.Buy ? (incoming.LimitPrice, open.LimitPrice) : (open.LimitPrice, incoming.LimitPrice); + return buy >= sell; + } + + private decimal RoundAdverse(PaperOrder order, decimal price) + { + var tick = _instruments(order.Request.Symbol)?.TickSize; + price = DbValues.Money(price); + return tick is > 0m ? (order.Request.Side == OrderSide.Buy ? OrderRules.RoundUp(price, tick.Value) : OrderRules.RoundDown(price, tick.Value)) : price; + } + + private void Finish(PaperOrder order, OrderStatus status, string reason) + { + order.Status = order.Filled > 0m && status == OrderStatus.Rejected ? OrderStatus.Canceled : status; + order.Reason = reason; + order.UpdatedAt = _clock.UtcNow; + Publish(order, null); + } + + private void Publish(PaperOrder order, BrokerFill? fill) => _updates.Writer.TryWrite(new OrderUpdate(ToBroker(order), fill)); + + private static bool IsOpen(PaperOrder order) => order.Status is OrderStatus.Created or OrderStatus.Submitted or OrderStatus.PartiallyFilled; + + private static BrokerOrder ToBroker(PaperOrder o) => new(o.Request.ClientOrderId, o.BrokerOrderId, o.Request.Symbol, o.Request.Side, o.Request.Kind, + o.Request.Quantity, o.Status, o.Filled, o.UpdatedAt) + { + LimitPrice = o.Request.LimitPrice, + StopPrice = o.Request.StopPrice, + TimeInForce = o.Request.TimeInForce, + AverageFillPrice = o.Filled > 0m ? DbValues.Money(o.FilledValue / o.Filled) : null, + Reason = o.Reason, + }; + + private TimeSpan Latency(long sequence) + { + var x = _options.Seed + ((ulong)sequence * 0x9E3779B97F4A7C15UL); + x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9UL; + x = (x ^ (x >> 27)) * 0x94D049BB133111EBUL; + x ^= x >> 31; + var span = (_options.MaxLatency - _options.MinLatency).Ticks; + return _options.MinLatency + TimeSpan.FromTicks(span <= 0 ? 0 : (long)(x % (ulong)span)); + } + + private static string NextId(PaperBook book, string prefix) => "SIM" + prefix + (++book.Sequence).ToString("D8", CultureInfo.InvariantCulture); + + private async Task SnapshotAsync(CancellationToken cancellationToken) + { + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + await EnsureLoadedAsync(cancellationToken).ConfigureAwait(false); + return JsonSerializer.Deserialize(JsonSerializer.Serialize(_book))!; + } + finally + { + _gate.Release(); + } + } + + private async Task WithBookAsync(Func change, CancellationToken cancellationToken) + { + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + await EnsureLoadedAsync(cancellationToken).ConfigureAwait(false); + if (change(_book) && _store is not null) + { + await _store.SaveAsync(_book, cancellationToken).ConfigureAwait(false); + } + } + finally + { + _gate.Release(); + } + } + + private async Task EnsureLoadedAsync(CancellationToken cancellationToken) + { + if (_loaded) + { + return; + } + + _book = (_store is null ? null : await _store.LoadAsync(cancellationToken).ConfigureAwait(false)) ?? new PaperBook { SeenUntil = _clock.UtcNow }; + _loaded = true; + } + + public void Dispose() => _gate.Dispose(); +} diff --git a/src/Anubis/Trading/Reconciler.cs b/src/Anubis/Trading/Reconciler.cs new file mode 100644 index 0000000..abf0404 --- /dev/null +++ b/src/Anubis/Trading/Reconciler.cs @@ -0,0 +1,536 @@ +using System.Globalization; +using System.Text.Json; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; + +namespace Anubis.Trading; + +/// Modes of an account (SPEC 7.4): in prudent mode no new entry goes out; exits and stops carry on. +public static class AccountModes +{ + public const string Normal = "normal"; + public const string Prudent = "prudent"; +} + +public static class ReconcileOutcomes +{ + /// Ledger and account agree. + public const string Clean = "clean"; + + /// They differed, and the difference explained itself: a late fill, a lost update, a split, a stop to put back. + public const string Healed = "healed"; + + /// An unexplained difference remains. + public const string Different = "different"; + + /// The broker could not be reached: nothing is concluded. + public const string Unreachable = "unreachable"; + + public const string UserAligned = "user_aligned"; + public const string UserExcluded = "user_excluded"; +} + +public static class DifferenceKinds +{ + /// The ledger holds more than the account. + public const string Position = "position"; + + /// An open order of this installation the bot does not know, or one it believes open that the broker does not have. + public const string Order = "order"; + + /// The account has less cash than the ledger gives the bot (real accounts only). + public const string Cash = "cash"; + + /// The stops on the broker do not cover the quantity held. + public const string Stop = "stop"; + + /// The ledger disagrees with itself: lots and position, or negative cash. + public const string Ledger = "ledger"; + + /// The key may withdraw (SPEC 2.2). + public const string Key = "key"; +} + +/// One difference between the bot's ledger and the account, with the message the user reads. +public sealed record AccountDifference(string Kind, string Subject, decimal Ledger, decimal Broker, string Message) +{ + public Guid? InstrumentId { get; init; } + + /// What an exclusion matches: the same thing with the same numbers. A new divergence shows up again. + public string Fingerprint => string.Create(CultureInfo.InvariantCulture, $"{Kind}:{Subject}:{Ledger}:{Broker}"); +} + +public sealed record ReconcileReport(Guid AccountId, string Outcome, IReadOnlyList Differences, IReadOnlyList Healed, string Mode); + +/// What the Conti screen shows of an account's state. +public sealed record AccountState(Guid AccountId, string Mode, DateTimeOffset? ModeSince, string? ModeReason, IReadOnlyList Differences, + IReadOnlyList Excluded, DateTimeOffset? LastReconciledAt, string? LastOutcome, bool? KeyCanTrade, bool? KeyCanWithdraw, DateTimeOffset? KeyCheckedAt) +{ + public static AccountState Initial(Guid accountId) => new(accountId, AccountModes.Normal, null, null, [], [], null, null, null, null, null); + + public bool IsPrudent => Mode == AccountModes.Prudent; + + /// The 15 minutes have passed and the difference is still there: only the user can close it (SPEC 7.4). + public bool WaitsForUser(DateTimeOffset now, TimeSpan grace) => + IsPrudent && ModeReason != Reconciler.KeyReason && Differences.Count > 0 && ModeSince is { } since && now - since >= grace; +} + +public enum ReconcileChoice +{ + /// The ledger takes the account's numbers, with an adjustment row. + Align, + + /// What differs stays out of the ledger and is no longer reported. + Exclude, +} + +/// +/// Reconciliation (SPEC 7.4), at start and every 5 minutes. What is compared depends on the environment: in the +/// internal simulator the ledger's own coherence; on demo accounts positions, orders and stops; on real accounts +/// cash as well. A difference first gets the chance to explain itself; one that does not puts the account in +/// prudent mode, which ends by itself within 15 minutes or by the user's choice. +/// +public sealed class Reconciler(Database db, IClock clock, Ledger ledger) +{ + public const string KeyReason = "key_can_withdraw"; + + /// How long a difference may take to explain itself before the user is asked. + public TimeSpan Grace { get; init; } = TimeSpan.FromMinutes(15); + + /// Cash below this is a rounding, not a difference. + public decimal CashTolerance { get; init; } = 0.01m; + + public async Task ReconcileAsync(OrderManager manager, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(manager); + var account = manager.Account; + var state = await StateAsync(account.AccountId, cancellationToken).ConfigureAwait(false); + var healed = new List(); + List differences; + try + { + differences = await CompareAsync(manager, cancellationToken).ConfigureAwait(false); + if (differences.Count > 0) + { + healed.AddRange(await HealAsync(manager, differences, cancellationToken).ConfigureAwait(false)); + var before = differences.Select(d => d.Fingerprint).ToHashSet(StringComparer.Ordinal); + differences = await CompareAsync(manager, cancellationToken).ConfigureAwait(false); + healed.AddRange(before.Except(differences.Select(d => d.Fingerprint), StringComparer.Ordinal)); + } + } + catch (BrokerException ex) + { + await RecordUnreachableAsync(account, state, ex.Message, cancellationToken).ConfigureAwait(false); + return new ReconcileReport(account.AccountId, ReconcileOutcomes.Unreachable, [], [], state.Mode); + } + + var excluded = state.Excluded.ToHashSet(StringComparer.Ordinal); + differences = differences.Where(d => !excluded.Contains(d.Fingerprint)).ToList(); + var outcome = differences.Count > 0 ? ReconcileOutcomes.Different : healed.Count > 0 ? ReconcileOutcomes.Healed : ReconcileOutcomes.Clean; + var mode = await RecordAsync(account, state, outcome, differences, healed, cancellationToken).ConfigureAwait(false); + return new ReconcileReport(account.AccountId, outcome, differences, healed, mode); + } + + /// + /// Reads what the key may do and keeps it with the account. A key that may withdraw is never used for new + /// entries (SPEC 2.2): the account goes prudent and only the user can bring it back, with another key. + /// + public async Task CheckKeyAsync(OrderManager manager, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(manager); + var account = manager.Account; + KeyPermissions permissions; + try + { + permissions = await manager.Broker.GetKeyPermissionsAsync(cancellationToken).ConfigureAwait(false); + } + catch (BrokerException) + { + return null; + } + + var now = clock.UtcNow; + await db.WriteAsync(async s => + { + await EnsureStatusAsync(s, account.AccountId, now, cancellationToken).ConfigureAwait(false); + await s.ExecuteAsync("UPDATE account_status SET key_can_trade = @t, key_can_withdraw = @w, key_checked_at = @now, updated_at = @now WHERE account_id = @a", cancellationToken, + ("t", permissions.CanTrade), ("w", permissions.CanWithdraw), ("now", now), ("a", account.AccountId)).ConfigureAwait(false); + if (permissions.CanWithdraw) + { + var difference = new AccountDifference(DifferenceKinds.Key, account.Name, 0m, 1m, $"La chiave del conto {account.Name} permette i prelievi: non la uso per nuovi acquisti."); + await s.ExecuteAsync("UPDATE account_status SET mode = @m, mode_since = @now, mode_reason = @r, differences = @d, updated_at = @now WHERE account_id = @a", cancellationToken, + ("m", AccountModes.Prudent), ("now", now), ("r", KeyReason), ("d", Stored([difference], [])), ("a", account.AccountId)).ConfigureAwait(false); + await Diary.NotifyAsync(s, clock, "key_can_withdraw", + $"La chiave del conto {account.Name} permette i prelievi. Non faccio nuovi acquisti su quel conto: sostituiscila con una chiave senza prelievo.", cancellationToken).ConfigureAwait(false); + } + }, cancellationToken).ConfigureAwait(false); + return permissions; + } + + /// + /// The user's choice after the 15 minutes (SPEC 7.4). Align: positions and cash of the ledger take the account's + /// numbers with adjustment rows. Exclude: what differs is left out and no longer reported. Either way the + /// account returns to normal; a later difference starts over. + /// + public async Task ResolveAsync(OrderManager manager, ReconcileChoice choice, string by, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(manager); + var account = manager.Account; + var state = await StateAsync(account.AccountId, cancellationToken).ConfigureAwait(false); + if (state.ModeReason == KeyReason) + { + throw new InvalidOperationException("A key that may withdraw is replaced, not aligned."); + } + + var excluded = state.Excluded.ToList(); + if (choice == ReconcileChoice.Align) + { + foreach (var difference in state.Differences) + { + if (!await AlignAsync(account, difference, cancellationToken).ConfigureAwait(false)) + { + // An order or the ledger's own coherence cannot be copied from the account: it is left out instead. + excluded.Add(difference.Fingerprint); + } + } + } + else + { + excluded.AddRange(state.Differences.Select(d => d.Fingerprint)); + } + + var now = clock.UtcNow; + var outcome = choice == ReconcileChoice.Align ? ReconcileOutcomes.UserAligned : ReconcileOutcomes.UserExcluded; + await db.WriteAsync(async s => + { + await EnsureStatusAsync(s, account.AccountId, now, cancellationToken).ConfigureAwait(false); + await s.ExecuteAsync("UPDATE account_status SET mode = @m, mode_since = @now, mode_reason = NULL, differences = @d, last_outcome = @o, updated_at = @now WHERE account_id = @a", + cancellationToken, ("m", AccountModes.Normal), ("now", now), ("d", Stored([], excluded.Distinct(StringComparer.Ordinal).ToList())), ("o", outcome), + ("a", account.AccountId)).ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO reconciliations (id, account_id, outcome, details, occurred_at, created_at) VALUES (@id, @a, @o, @d, @now, @now)", cancellationToken, + ("id", Ids.NewId(clock)), ("a", account.AccountId), ("o", outcome), ("d", new DbJson(JsonSerializer.Serialize(new { by, differences = state.Differences }))), + ("now", now)).ConfigureAwait(false); + var what = choice == ReconcileChoice.Align ? "ho allineato il registro al conto" : "ho lasciato fuori dal registro ciò che non è mio"; + await Diary.WriteAsync(s, clock, DiaryKinds.System, "account_resolved", $"Conto {account.Name}: {what}, come hai scelto. Il conto torna normale.", + null, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + } + + public Task StateAsync(Guid accountId, CancellationToken cancellationToken) => + db.ReadAsync(async s => await s.FirstOrDefaultAsync( + "SELECT mode, mode_since, mode_reason, differences, last_reconciled_at, last_outcome, key_can_trade, key_can_withdraw, key_checked_at FROM account_status WHERE account_id = @a", + r => + { + var stored = r.IsNull("differences") ? null : JsonSerializer.Deserialize(r.Json("differences").Text); + return new AccountState(accountId, r.Text("mode"), r.MomentOrNull("mode_since"), r.TextOrNull("mode_reason"), stored?.Current ?? [], stored?.Excluded ?? [], + r.MomentOrNull("last_reconciled_at"), r.TextOrNull("last_outcome"), r.IsNull("key_can_trade") ? null : r.Bool("key_can_trade"), + r.IsNull("key_can_withdraw") ? null : r.Bool("key_can_withdraw"), r.MomentOrNull("key_checked_at")); + }, ("a", accountId)).ConfigureAwait(false) ?? AccountState.Initial(accountId), cancellationToken); + + /// Every difference between the ledger and the account, before anything is healed. + public async Task> CompareAsync(OrderManager manager, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(manager); + var account = manager.Account; + var differences = await CoherenceAsync(account, cancellationToken).ConfigureAwait(false); + var positions = await ledger.PositionsAsync(account.AccountId, cancellationToken).ConfigureAwait(false); + var instruments = new Dictionary(); + foreach (var id in positions.Select(p => p.InstrumentId).Distinct()) + { + if (await manager.FindInstrumentAsync(id, cancellationToken).ConfigureAwait(false) is { } instrument) + { + instruments[id] = instrument; + } + } + + var brokerOrders = await manager.Broker.GetOpenOrdersAsync(cancellationToken).ConfigureAwait(false); + var ours = brokerOrders.Where(o => ClientOrderIds.IsOurs(o.ClientOrderId, manager.InstallationCode)).ToList(); + differences.AddRange(await StopCoverageAsync(manager, positions, instruments, ours, cancellationToken).ConfigureAwait(false)); + if (account.Environment == TradingEnvironments.Simulation) + { + // The internal simulator is the bot's own: there is no other book to compare with (SPEC 7.4). + return differences; + } + + var held = await manager.Broker.GetPositionsAsync(cancellationToken).ConfigureAwait(false); + foreach (var group in positions.GroupBy(p => p.InstrumentId)) + { + if (!instruments.TryGetValue(group.Key, out var instrument)) + { + continue; + } + + var mine = group.Sum(p => p.Quantity); + var there = held.Where(h => h.Symbol == instrument.Symbol).Sum(h => h.Quantity); + var tolerance = Math.Max(OrderRules.LotOf(instrument.Spec), 0.00000001m); + + // More on the account than in the ledger is the user's own (SPEC 7.1): only less is a difference. + if (there < mine - tolerance) + { + differences.Add(new AccountDifference(DifferenceKinds.Position, instrument.Symbol, mine, there, + $"{instrument.Symbol}: il registro dice {Format.Quantity(mine)}, sul conto ce ne sono {Format.Quantity(there)}.") + { InstrumentId = instrument.Id }); + } + } + + var known = await manager.OpenOrdersAsync(cancellationToken).ConfigureAwait(false); + var knownIds = known.Select(k => k.ClientOrderId).ToHashSet(StringComparer.Ordinal); + foreach (var order in ours.Where(o => !knownIds.Contains(o.ClientOrderId))) + { + differences.Add(new AccountDifference(DifferenceKinds.Order, order.ClientOrderId, 0m, order.Remaining, + $"Sul conto c'è un mio ordine aperto che non conosco: {order.ClientOrderId} ({order.Symbol}).")); + } + + var open = ours.Select(o => o.ClientOrderId).ToHashSet(StringComparer.Ordinal); + foreach (var order in known.Where(k => !open.Contains(k.ClientOrderId))) + { + differences.Add(new AccountDifference(DifferenceKinds.Order, order.ClientOrderId, 1m, 0m, + $"Credo aperto l'ordine {order.ClientOrderId}, ma il conto non lo ha.") + { InstrumentId = order.InstrumentId }); + } + + if (account.Environment == TradingEnvironments.Live) + { + // A demo account holds play money in any amount: only a real account's cash is compared (SPEC 7.4). + var snapshot = await manager.Broker.GetAccountAsync(cancellationToken).ConfigureAwait(false); + var there = snapshot.Cash.TryGetValue(account.Currency, out var cash) ? cash : 0m; + var mine = (await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false)).Where(e => e.AccountId == account.AccountId).Sum(e => e.Cash); + if (there < mine - CashTolerance) + { + differences.Add(new AccountDifference(DifferenceKinds.Cash, account.Currency, mine, there, + $"Liquidità: il registro mi attribuisce {Format.Quantity(mine)} {account.Currency}, sul conto ce ne sono {Format.Quantity(there)}.")); + } + } + + return differences; + } + + private async Task> CoherenceAsync(AccountContext account, CancellationToken cancellationToken) + { + var differences = new List(); + var rows = await db.ReadAsync(s => s.QueryAsync("SELECT instrument_id, strategy, quantity FROM positions WHERE account_id = @a", + r => (Instrument: r.Id("instrument_id"), Strategy: r.Text("strategy"), Quantity: r.Money("quantity")), ("a", account.AccountId)), cancellationToken).ConfigureAwait(false); + foreach (var row in rows) + { + var lots = (await ledger.OpenLotsAsync(account.AccountId, row.Instrument, row.Strategy, cancellationToken).ConfigureAwait(false)).Sum(l => l.Remaining); + if (row.Quantity < -Ledger.Dust || Math.Abs(lots - row.Quantity) > Ledger.Dust * 1000m) + { + differences.Add(new AccountDifference(DifferenceKinds.Ledger, $"{row.Strategy}:{row.Instrument}", row.Quantity, lots, + $"Il registro non torna con sé stesso ({row.Strategy}): posizione {Format.Quantity(row.Quantity)}, lotti {Format.Quantity(lots)}.") + { InstrumentId = row.Instrument }); + } + } + + foreach (var equity in (await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false)).Where(e => e.AccountId == account.AccountId && e.Cash < -CashTolerance)) + { + differences.Add(new AccountDifference(DifferenceKinds.Ledger, $"{equity.Strategy}:cash", equity.Cash, 0m, + $"La liquidità di {equity.Strategy} nel registro è negativa: {Format.Quantity(equity.Cash)} {equity.Currency}.")); + } + + return differences; + } + + private static async Task> StopCoverageAsync(OrderManager manager, IReadOnlyList positions, Dictionary instruments, + List ours, CancellationToken cancellationToken) + { + var differences = new List(); + var working = (await manager.WorkingInstrumentsAsync(cancellationToken).ConfigureAwait(false)).ToHashSet(); + foreach (var group in positions.Where(p => p.StopPrice is not null).GroupBy(p => p.InstrumentId)) + { + if (working.Contains(group.Key) || !instruments.TryGetValue(group.Key, out var instrument)) + { + // While a buy or a sale is under way the stops are moved on purpose and the bot watches the level (SPEC 7.2). + continue; + } + + var open = manager.MarketOpen is null || await manager.MarketOpen(instrument, cancellationToken).ConfigureAwait(false); + var required = group.Sum(p => manager.DesiredStops(instrument, p.Quantity).Where(d => d.TimeInForce != TimeInForce.Day || open).Sum(d => d.Quantity)); + var covered = ours.Where(o => o.Symbol == instrument.Symbol && o.Kind == OrderKind.Stop && o.Side == OrderSide.Sell).Sum(o => o.Remaining); + if (covered < required - Ledger.Dust) + { + differences.Add(new AccountDifference(DifferenceKinds.Stop, instrument.Symbol, required, covered, + $"{instrument.Symbol}: gli stop coprono {Format.Quantity(covered)} su {Format.Quantity(required)}.") + { InstrumentId = instrument.Id }); + } + } + + return differences; + } + + /// The explanations tried before a difference counts: late fills and updates, splits, stops put back. + private static async Task> HealAsync(OrderManager manager, List differences, CancellationToken cancellationToken) + { + var notes = new List(); + await manager.RefreshAsync(cancellationToken).ConfigureAwait(false); + foreach (var difference in differences.Where(d => d.Kind == DifferenceKinds.Order && d.Ledger == 0m)) + { + var remote = (await manager.Broker.GetOpenOrdersAsync(cancellationToken).ConfigureAwait(false)).FirstOrDefault(o => o.ClientOrderId == difference.Subject); + if (remote is not null && await manager.AdoptOpenOrderAsync(remote, cancellationToken).ConfigureAwait(false)) + { + notes.Add("order:" + difference.Subject); + } + } + + if (manager.PendingSplit is not null) + { + foreach (var difference in differences.Where(d => d.Kind == DifferenceKinds.Position && d.InstrumentId is not null)) + { + if (await manager.FindInstrumentAsync(difference.InstrumentId!.Value, cancellationToken).ConfigureAwait(false) is { } instrument + && await manager.PendingSplit(instrument, cancellationToken).ConfigureAwait(false) is { } split) + { + await manager.ApplySplitAsync(instrument, split, cancellationToken).ConfigureAwait(false); + notes.Add("split:" + instrument.Symbol); + } + } + } + + if (differences.Any(d => d.Kind == DifferenceKinds.Stop)) + { + await manager.AlignStopsAsync(cancellationToken).ConfigureAwait(false); + } + + return notes; + } + + private async Task AlignAsync(AccountContext account, AccountDifference difference, CancellationToken cancellationToken) + { + var note = "Allineamento scelto dall'utente dopo la riconciliazione"; + if (difference.Kind == DifferenceKinds.Position && difference.InstrumentId is { } instrumentId) + { + // The missing quantity comes off the largest holders first. + var missing = difference.Ledger - difference.Broker; + var holders = (await ledger.PositionsAsync(account.AccountId, cancellationToken).ConfigureAwait(false)) + .Where(p => p.InstrumentId == instrumentId).OrderByDescending(p => p.Quantity).ToList(); + foreach (var holder in holders) + { + if (missing <= 0m) + { + break; + } + + var take = Math.Min(holder.Quantity, missing); + await ledger.AdjustQuantityAsync(account.AccountId, instrumentId, holder.Strategy, -take, holder.LastPrice ?? holder.AveragePrice, note, cancellationToken) + .ConfigureAwait(false); + missing -= take; + } + + return true; + } + + if (difference.Kind == DifferenceKinds.Cash) + { + var missing = difference.Ledger - difference.Broker; + var holders = (await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false)) + .Where(e => e.AccountId == account.AccountId && e.Cash > 0m).OrderByDescending(e => e.Cash).ToList(); + foreach (var holder in holders) + { + if (missing <= 0m) + { + break; + } + + var take = Math.Min(holder.Cash, missing); + await ledger.AdjustCashAsync(account.AccountId, holder.Strategy, -take, account.Currency, note, cancellationToken).ConfigureAwait(false); + missing -= take; + } + + return true; + } + + return false; + } + + private async Task RecordAsync(AccountContext account, AccountState state, string outcome, List differences, List healed, + CancellationToken cancellationToken) + { + var now = clock.UtcNow; + var mode = state.Mode; + var since = state.ModeSince; + var reason = state.ModeReason; + var stored = state.Differences; + string? diary = null; + var notify = false; + if (differences.Count > 0) + { + stored = differences; + if (mode == AccountModes.Normal) + { + mode = AccountModes.Prudent; + since = now; + reason = differences[0].Kind; + notify = true; + diary = $"Ho messo il conto {account.Name} in modalità prudente: {differences[0].Message} Niente nuovi acquisti finché non si chiarisce; vendite e stop proseguono."; + } + } + else if (mode == AccountModes.Prudent && reason != KeyReason && since is { } start && now - start < Grace) + { + mode = AccountModes.Normal; + since = now; + reason = null; + stored = []; + diary = $"La differenza sul conto {account.Name} si è spiegata da sola: il conto torna normale."; + } + + await db.WriteAsync(async s => + { + await EnsureStatusAsync(s, account.AccountId, now, cancellationToken).ConfigureAwait(false); + await s.ExecuteAsync("UPDATE account_status SET mode = @m, mode_since = @since, mode_reason = @r, differences = @d, last_reconciled_at = @now, last_outcome = @o, updated_at = @now " + + "WHERE account_id = @a", cancellationToken, + ("m", mode), ("since", since), ("r", reason), ("d", Stored(stored, state.Excluded)), ("now", now), ("o", outcome), ("a", account.AccountId)).ConfigureAwait(false); + + // A clean round is not worth a row every 5 minutes; differences and healings are. + if (outcome != ReconcileOutcomes.Clean) + { + await s.ExecuteAsync("INSERT INTO reconciliations (id, account_id, outcome, details, occurred_at, created_at) VALUES (@id, @a, @o, @d, @now, @now)", cancellationToken, + ("id", Ids.NewId(clock)), ("a", account.AccountId), ("o", outcome), ("d", new DbJson(JsonSerializer.Serialize(new { differences, healed }))), ("now", now)) + .ConfigureAwait(false); + } + + if (outcome == ReconcileOutcomes.Healed) + { + await Diary.WriteAsync(s, clock, DiaryKinds.System, "reconcile_healed", + $"Riconciliazione del conto {account.Name}: c'era una differenza che si è spiegata da sola ({string.Join(", ", healed)}).", null, cancellationToken).ConfigureAwait(false); + } + + if (diary is not null) + { + if (notify) + { + await Diary.NotifyAsync(s, clock, "account_prudent", diary, cancellationToken).ConfigureAwait(false); + } + else + { + await Diary.WriteAsync(s, clock, DiaryKinds.System, "account_normal", diary, null, cancellationToken).ConfigureAwait(false); + } + } + }, cancellationToken).ConfigureAwait(false); + return mode; + } + + private async Task RecordUnreachableAsync(AccountContext account, AccountState state, string message, CancellationToken cancellationToken) + { + var now = clock.UtcNow; + await db.WriteAsync(async s => + { + await EnsureStatusAsync(s, account.AccountId, now, cancellationToken).ConfigureAwait(false); + await s.ExecuteAsync("UPDATE account_status SET last_outcome = @o, updated_at = @now WHERE account_id = @a", cancellationToken, + ("o", ReconcileOutcomes.Unreachable), ("now", now), ("a", account.AccountId)).ConfigureAwait(false); + if (state.LastOutcome != ReconcileOutcomes.Unreachable) + { + await Diary.WriteAsync(s, clock, DiaryKinds.System, "reconcile_unreachable", + $"Non riesco a riconciliare il conto {account.Name}: il broker non risponde. Riprovo tra 5 minuti.", new { message = Redactor.Redact(message) }, cancellationToken) + .ConfigureAwait(false); + } + }, cancellationToken).ConfigureAwait(false); + } + + private async Task EnsureStatusAsync(DbSession s, Guid accountId, DateTimeOffset now, CancellationToken cancellationToken) => + await s.ExecuteAsync("INSERT INTO account_status (id, account_id, mode, created_at, updated_at) VALUES (@id, @a, @m, @now, @now) ON CONFLICT (account_id) DO NOTHING", + cancellationToken, ("id", Ids.NewId(clock)), ("a", accountId), ("m", AccountModes.Normal), ("now", now)).ConfigureAwait(false); + + private static DbJson Stored(IReadOnlyList current, IReadOnlyList excluded) => + new(JsonSerializer.Serialize(new StoredDifferences(current.ToList(), excluded.ToList()))); + + private sealed record StoredDifferences(List Current, List Excluded); +} diff --git a/src/Anubis/Trading/TradingHttp.cs b/src/Anubis/Trading/TradingHttp.cs new file mode 100644 index 0000000..8622b5b --- /dev/null +++ b/src/Anubis/Trading/TradingHttp.cs @@ -0,0 +1,92 @@ +using System.Net; +using System.Text; +using Anubis.Brokers; +using Anubis.Core; + +namespace Anubis.Trading; + +/// An answer of a broker: status code and body, whatever the status. +public sealed record HttpAnswer(HttpStatusCode Status, string Body) +{ + public bool Ok => (int)Status is >= 200 and < 300; +} + +/// +/// Requests to a broker's trading API. Reads and cancellations are retried on network errors, 429 and server +/// errors; an order is sent once and never retried here: when its answer is lost the order manager asks the +/// broker before sending again with the same id (SPEC 7.2). Errors never carry headers, so keys stay out of logs. +/// +public sealed class TradingHttp(HttpClient http, IClock clock, string sourceName) +{ + public const int Attempts = 3; + + public string SourceName { get; } = sourceName; + + public async Task SendAsync(HttpMethod method, Uri url, string? body, Func> headers, RateLimiter? limiter, bool retry, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(method); + ArgumentNullException.ThrowIfNull(url); + ArgumentNullException.ThrowIfNull(headers); + for (var attempt = 1; ; attempt++) + { + if (limiter is not null) + { + await limiter.WaitAsync(cancellationToken).ConfigureAwait(false); + } + + using var request = new HttpRequestMessage(method, url); + if (body is not null) + { + request.Content = new StringContent(body, Encoding.UTF8, "application/json"); + } + + foreach (var (name, value) in headers(body ?? "")) + { + request.Headers.TryAddWithoutValidation(name, value); + } + + HttpResponseMessage response; + try + { + response = await http.SendAsync(request, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is HttpRequestException || (ex is TaskCanceledException && !cancellationToken.IsCancellationRequested)) + { + if (retry && attempt < Attempts) + { + await WaitAsync(attempt, cancellationToken).ConfigureAwait(false); + continue; + } + + throw new BrokerException($"{SourceName}: nessuna risposta da {ApiHttp.Describe(url)}.", retryable: true, ex); + } + + using (response) + { + var text = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + if (response.StatusCode == HttpStatusCode.TooManyRequests || (int)response.StatusCode >= 500) + { + if (retry && attempt < Attempts) + { + await WaitAsync(attempt, cancellationToken).ConfigureAwait(false); + continue; + } + + throw new BrokerException($"{SourceName}: risposta {(int)response.StatusCode} da {ApiHttp.Describe(url)}.", retryable: true); + } + + return new HttpAnswer(response.StatusCode, text); + } + } + } + + public BrokerException Failure(Uri url, HttpAnswer answer) + { + ArgumentNullException.ThrowIfNull(answer); + var text = answer.Body.Length <= 300 ? answer.Body : answer.Body[..300] + "…"; + return new BrokerException($"{SourceName}: risposta {(int)answer.Status} da {ApiHttp.Describe(url)}: {Redactor.Redact(text)}", retryable: false); + } + + private Task WaitAsync(int attempt, CancellationToken cancellationToken) => + clock.WaitUntilAsync(clock.UtcNow + TimeSpan.FromSeconds(Math.Pow(2, attempt)), cancellationToken); +} diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs new file mode 100644 index 0000000..b6d458e --- /dev/null +++ b/src/Anubis/Trading/TradingService.cs @@ -0,0 +1,585 @@ +using System.Collections.Concurrent; +using Anubis.Brokers; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Anubis.Trading; + +/// +/// The last quote of every symbol: from the live stream when it is fresh, otherwise asked by REST. The second +/// reading of the stop already passed always goes to REST (SPEC 7.2). +/// +public sealed class QuoteBook(IClock clock, Func>? fetch = null) +{ + private readonly ConcurrentDictionary _quotes = new(StringComparer.Ordinal); + + public TimeSpan MaxAge { get; init; } = TimeSpan.FromSeconds(60); + + public void Put(Quote quote) + { + ArgumentNullException.ThrowIfNull(quote); + _quotes.AddOrUpdate(quote.Symbol, quote, (_, old) => quote.At >= old.At ? quote : old); + } + + public async Task GetAsync(string symbol, CancellationToken cancellationToken) + { + if (_quotes.TryGetValue(symbol, out var cached) && clock.UtcNow - cached.At <= MaxAge) + { + return cached; + } + + return await ConfirmAsync(symbol, cancellationToken).ConfigureAwait(false) ?? cached; + } + + public async Task ConfirmAsync(string symbol, CancellationToken cancellationToken) + { + if (fetch is null) + { + return null; + } + + try + { + var quote = await fetch(symbol, cancellationToken).ConfigureAwait(false); + if (quote is not null) + { + Put(quote); + } + + return quote; + } + catch (Exception ex) when (ex is MarketDataException or HttpRequestException or TaskCanceledException && !cancellationToken.IsCancellationRequested) + { + return null; + } + } +} + +/// +/// The accounts of this installation (SPEC 7.1): the internal simulator for each broker is always there; a demo +/// account exists when its keys do. Real accounts are never created in this phase (SPEC 2.2). +/// +public static class AccountSetup +{ + public static string NameOf(string broker, string environment) => (broker, environment) switch + { + (Venues.Okx, TradingEnvironments.Simulation) => "OKX simulatore", + (Venues.Alpaca, TradingEnvironments.Simulation) => "Alpaca simulatore", + (Venues.Okx, TradingEnvironments.Demo) => "OKX demo", + (Venues.Alpaca, TradingEnvironments.Demo) => "Alpaca paper", + _ => $"{broker} {environment}", + }; + + public static async Task> EnsureAsync(Database db, IClock clock, bool alpacaDemo, bool okxDemo, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(db); + ArgumentNullException.ThrowIfNull(clock); + var wanted = new List<(string Broker, string Environment)> { (Venues.Okx, TradingEnvironments.Simulation), (Venues.Alpaca, TradingEnvironments.Simulation) }; + if (okxDemo) + { + wanted.Add((Venues.Okx, TradingEnvironments.Demo)); + } + + if (alpacaDemo) + { + wanted.Add((Venues.Alpaca, TradingEnvironments.Demo)); + } + + return await db.WriteAsync>(async s => + { + var now = clock.UtcNow; + foreach (var (broker, environment) in wanted) + { + if (await s.CountAsync("SELECT COUNT(*) FROM accounts WHERE broker = @b AND environment = @e", ("b", broker), ("e", environment)).ConfigureAwait(false) == 0) + { + await s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, @n, @b, @e, @c, @now)", cancellationToken, + ("id", Ids.NewId(clock)), ("n", NameOf(broker, environment)), ("b", broker), ("e", environment), ("c", Strategies.CurrencyOf(broker)), ("now", now)) + .ConfigureAwait(false); + } + } + + var accounts = await s.QueryAsync("SELECT id, name, broker, environment, base_currency FROM accounts ORDER BY created_at, id", + r => new AccountContext(r.Id("id"), r.Text("name"), r.Text("broker"), r.Text("environment"), r.Text("base_currency"))).ConfigureAwait(false); + + // By default crypto runs in the internal simulator and stocks in the demo account (SPEC 7.1). A strategy + // whose ledger is still empty follows the default when a demo account appears; one with a history stays. + foreach (var (strategy, broker, share) in Strategies.Base) + { + var environment = broker == Venues.Alpaca && alpacaDemo ? TradingEnvironments.Demo : TradingEnvironments.Simulation; + var target = accounts.First(a => a.Broker == broker && a.Environment == environment).AccountId; + var current = await s.FirstOrDefaultAsync("SELECT account_id FROM strategy_state WHERE strategy = @s", r => r.IdOrNull("account_id"), ("s", strategy)) + .ConfigureAwait(false); + if (current is null && await s.CountAsync("SELECT COUNT(*) FROM strategy_state WHERE strategy = @s", ("s", strategy)).ConfigureAwait(false) == 0) + { + await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share) VALUES (@id, @s, @a, @st, 0, @j, @now, @now, @sh)", + cancellationToken, ("id", Ids.NewId(clock)), ("s", strategy), ("a", target), ("st", Strategies.Observation), ("j", new DbJson("{}")), ("now", now), ("sh", share)) + .ConfigureAwait(false); + } + else if (current != target + && await s.CountAsync("SELECT COUNT(*) FROM cash_ledger WHERE strategy = @s", ("s", strategy)).ConfigureAwait(false) == 0 + && await s.CountAsync("SELECT COUNT(*) FROM fills WHERE strategy = @s", ("s", strategy)).ConfigureAwait(false) == 0) + { + await s.ExecuteAsync("UPDATE strategy_state SET account_id = @a, updated_at = @now WHERE strategy = @s", cancellationToken, ("a", target), ("now", now), ("s", strategy)) + .ConfigureAwait(false); + } + } + + return accounts; + }, cancellationToken).ConfigureAwait(false); + } +} + +/// +/// Runs the accounts (SPEC 7): one order manager per account, reconciliation, equity photographs, corporate +/// actions. The broker of each account is the internal simulator, or the demo account with its keys; a real +/// account is refused unless the live switch is on, and this phase never creates one (SPEC 2.2). +/// +public sealed partial class TradingService : IDisposable +{ + private readonly Database _db; + private readonly IClock _clock; + private readonly EventBus _bus; + private readonly SecretStore _secrets; + private readonly MarketDataService? _market; + private readonly TradingConsent _consent; + private readonly HttpClient _http; + private readonly Func? _sockets; + private readonly ILogger _logger; + private readonly InstrumentCatalog _catalog; + private readonly BarStore _bars; + private readonly ConcurrentDictionary<(string Venue, string Symbol), InstrumentSpec> _specs = new(); + private readonly ConcurrentDictionary _managers = new(); + + public TradingService(Database db, IClock clock, EventBus bus, SecretStore secrets, MarketDataService? market, FxStore fx, TradingConsent consent, Guid installationId, + HttpMessageHandler? handler = null, Func? sockets = null, ILogger? logger = null) + { + _db = db ?? throw new ArgumentNullException(nameof(db)); + _clock = clock ?? throw new ArgumentNullException(nameof(clock)); + _bus = bus ?? throw new ArgumentNullException(nameof(bus)); + _secrets = secrets ?? throw new ArgumentNullException(nameof(secrets)); + _market = market; + _consent = consent ?? throw new ArgumentNullException(nameof(consent)); + _sockets = sockets; + _logger = logger ?? NullLogger.Instance; + _http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false); + _http.Timeout = TimeSpan.FromSeconds(30); + _http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}"); + _catalog = new InstrumentCatalog(db, clock); + _bars = new BarStore(db, clock); + InstallationCode = ClientOrderIds.InstallationCode(installationId); + Ledger = new Ledger(db, clock); + Reconciler = new Reconciler(db, clock, Ledger); + Capital = new Capital(db, clock, Ledger, fx); + Equity = new EquityBook(db, clock, Ledger, fx); + Quotes = new QuoteBook(clock, FetchQuoteAsync); + } + + public string InstallationCode { get; } + + public Ledger Ledger { get; } + + public Reconciler Reconciler { get; } + + public Capital Capital { get; } + + public EquityBook Equity { get; } + + public QuoteBook Quotes { get; } + + public TimeSpan TickInterval { get; init; } = TimeSpan.FromSeconds(5); + + public IReadOnlyCollection Managers => [.. _managers.Values]; + + public OrderManager? ManagerOf(Guid accountId) => _managers.GetValueOrDefault(accountId); + + /// Accounts, brokers and order managers; then the simulator catches up, keys are checked and every account reconciled. + public async Task StartAsync(CancellationToken cancellationToken) + { + var alpaca = await AlpacaKeysAsync(cancellationToken).ConfigureAwait(false); + var okx = await OkxKeysAsync(cancellationToken).ConfigureAwait(false); + var accounts = await AccountSetup.EnsureAsync(_db, _clock, alpaca is not null, okx is not null, cancellationToken).ConfigureAwait(false); + await RefreshSpecsAsync(cancellationToken).ConfigureAwait(false); + foreach (var account in accounts) + { + var broker = Build(account, alpaca, okx); + if (broker is null) + { + continue; + } + + _managers[account.AccountId] = new OrderManager(_db, _clock, Ledger, broker, account, InstallationCode, + (id, ct) => _catalog.GetAsync(id, ct), Quotes.GetAsync) + { + ConfirmPrice = Quotes.ConfirmAsync, + MarketOpen = MarketOpenAsync, + PendingSplit = (instrument, ct) => PendingSplitAsync(account.AccountId, instrument, ct), + AfterFills = async ct => await Equity.TakeAsync(ct).ConfigureAwait(false), + }; + } + + await GuardAsync("simulatore", () => FundSimulatorsAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + foreach (var manager in _managers.Values) + { + await GuardAsync("avvio " + manager.Account.Name, async () => + { + if (manager.Broker is PaperBroker paper) + { + await paper.CatchUpAsync(MinuteBarsAsync, cancellationToken).ConfigureAwait(false); + } + else + { + await Reconciler.CheckKeyAsync(manager, cancellationToken).ConfigureAwait(false); + } + + await Reconciler.ReconcileAsync(manager, cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + } + + await GuardAsync("patrimonio", () => Equity.TakeAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + } + + public IReadOnlyList Jobs() => + [ + new ScheduledJob("riconciliazione", "Riconciliazione dei conti", Schedule.Every(TimeSpan.FromMinutes(5)), ReconcileAllAsync), + new ScheduledJob("patrimonio", "Fotografia del patrimonio", Schedule.Every(TimeSpan.FromMinutes(5)), async ct => await Equity.TakeAsync(ct).ConfigureAwait(false)), + new ScheduledJob("azioni_societarie", "Dividendi e frazionamenti nei registri", Schedule.Every(TimeSpan.FromHours(1)), CorporateActionsAsync), + ]; + + /// The working loop: quotes from the stream, order updates from the brokers, a turn of every account every few seconds. + public async Task RunAsync(CancellationToken cancellationToken) + { + using var quotes = _bus.Subscribe(1024); + var streams = _managers.Values.Where(m => m.Broker is not PaperBroker).Select(m => FollowAsync(m, cancellationToken)).ToList(); + try + { + while (!cancellationToken.IsCancellationRequested) + { + while (quotes.TryRead(out var quote)) + { + Quotes.Put(quote!.Quote); + } + + await TickAllAsync(cancellationToken).ConfigureAwait(false); + await Task.Delay(TickInterval, cancellationToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + } + + await Task.WhenAll(streams).ConfigureAwait(false); + } + + public async Task TickAllAsync(CancellationToken cancellationToken) + { + foreach (var manager in _managers.Values) + { + await GuardAsync("ordini " + manager.Account.Name, async () => + { + if (manager.Broker is PaperBroker paper) + { + await paper.PumpAsync(cancellationToken).ConfigureAwait(false); + } + + await manager.TickAsync(cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + } + } + + public async Task ReconcileAllAsync(CancellationToken cancellationToken) + { + await RefreshSpecsAsync(cancellationToken).ConfigureAwait(false); + foreach (var manager in _managers.Values) + { + await Reconciler.ReconcileAsync(manager, cancellationToken).ConfigureAwait(false); + } + } + + /// + /// Cash dividends and splits reach the ledgers (SPEC 6.10, 7.5): a dividend goes to whoever held the stock at the + /// close before the ex-date, on the ex-date; a split changes quantities, prices and stops. Each is applied once. + /// + public async Task CorporateActionsAsync(CancellationToken cancellationToken) + { + var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime); + var actions = await _db.ReadAsync(s => s.QueryAsync( + "SELECT symbol, kind, ex_date, ratio, cash_amount, currency, new_symbol, source, source_key FROM corporate_actions WHERE ex_date <= @d ORDER BY ex_date", + r => new CorporateAction(r.Text("symbol"), r.Text("kind"), BarStore.ParseDay(r.Text("ex_date")), r.Text("source"), r.Text("source_key")) + { + Ratio = r.MoneyOrNull("ratio"), + CashAmount = r.MoneyOrNull("cash_amount"), + Currency = r.TextOrNull("currency"), + NewSymbol = r.TextOrNull("new_symbol"), + }, ("d", BarStore.DayText(today))), cancellationToken).ConfigureAwait(false); + foreach (var manager in _managers.Values.Where(m => m.Account.Broker == Venues.Alpaca)) + { + var positions = await Ledger.PositionsAsync(manager.Account.AccountId, cancellationToken).ConfigureAwait(false); + var held = new Dictionary(StringComparer.Ordinal); + foreach (var id in positions.Select(p => p.InstrumentId).Distinct()) + { + if (await _catalog.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } instrument) + { + held[instrument.Symbol] = instrument; + } + } + + foreach (var action in actions.Where(a => held.ContainsKey(a.Symbol))) + { + var instrument = held[action.Symbol]; + if (action.ChangesShares) + { + if (manager.Broker is PaperBroker paper && !await AppliedAsync(manager.Account.AccountId, action.SourceKey, cancellationToken).ConfigureAwait(false)) + { + await paper.ApplySplitAsync(action.Symbol, action.Ratio!.Value, cancellationToken).ConfigureAwait(false); + } + + await manager.ApplySplitAsync(instrument, action, cancellationToken).ConfigureAwait(false); + } + else if (action.Kind == CorporateActionKinds.CashDividend && action.CashAmount is > 0m) + { + await PayDividendAsync(manager, instrument, action, cancellationToken).ConfigureAwait(false); + } + } + } + } + + private async Task PayDividendAsync(OrderManager manager, Instrument instrument, CorporateAction action, CancellationToken cancellationToken) + { + var key = "div:" + action.SourceKey; + var account = manager.Account; + if (await AppliedAsync(account.AccountId, key, cancellationToken).ConfigureAwait(false)) + { + return; + } + + var exDate = new DateTimeOffset(action.ExDate.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + var strategies = (await Ledger.PositionsAsync(account.AccountId, cancellationToken).ConfigureAwait(false)) + .Where(p => p.InstrumentId == instrument.Id).Select(p => p.Strategy).Distinct(StringComparer.Ordinal).ToList(); + foreach (var strategy in strategies) + { + var quantity = await Ledger.QuantityAtAsync(account.AccountId, instrument.Id, strategy, exDate, cancellationToken).ConfigureAwait(false); + if (quantity <= 0m) + { + continue; + } + + var amount = Math.Round(quantity * action.CashAmount!.Value, 2, MidpointRounding.ToZero); + if (manager.Broker is PaperBroker paper) + { + await paper.PayDividendAsync(action.Symbol, action.CashAmount!.Value, action.Currency ?? account.Currency, exDate, cancellationToken).ConfigureAwait(false); + } + + await Ledger.RecordDividendAsync(account.AccountId, strategy, amount, action.Currency ?? account.Currency, exDate, + $"Dividendo {action.Symbol} {Format.Quantity(action.CashAmount!.Value)} per azione", cancellationToken).ConfigureAwait(false); + } + + await _db.WriteAsync(s => s.ExecuteAsync("INSERT INTO applied_actions (id, account_id, source_key, created_at) VALUES (@id, @a, @k, @now) ON CONFLICT (account_id, source_key) DO NOTHING", + cancellationToken, ("id", Ids.NewId(_clock)), ("a", account.AccountId), ("k", key), ("now", _clock.UtcNow)), cancellationToken).ConfigureAwait(false); + } + + private Task AppliedAsync(Guid accountId, string sourceKey, CancellationToken cancellationToken) => + _db.ReadAsync(async s => await s.CountAsync("SELECT COUNT(*) FROM applied_actions WHERE account_id = @a AND source_key = @k", ("a", accountId), ("k", sourceKey)) + .ConfigureAwait(false) > 0, cancellationToken); + + private async Task PendingSplitAsync(Guid accountId, Instrument instrument, CancellationToken cancellationToken) + { + var today = DateOnly.FromDateTime(_clock.UtcNow.UtcDateTime); + var splits = await _db.ReadAsync(s => s.QueryAsync( + "SELECT kind, ex_date, ratio, source, source_key FROM corporate_actions WHERE symbol = @s AND ex_date <= @d AND kind IN (@k1, @k2) ORDER BY ex_date DESC", + r => new CorporateAction(instrument.Symbol, r.Text("kind"), BarStore.ParseDay(r.Text("ex_date")), r.Text("source"), r.Text("source_key")) { Ratio = r.MoneyOrNull("ratio") }, + ("s", instrument.Symbol), ("d", BarStore.DayText(today)), ("k1", CorporateActionKinds.Split), ("k2", CorporateActionKinds.StockDividend)), cancellationToken) + .ConfigureAwait(false); + foreach (var split in splits.Where(s => s.ChangesShares)) + { + if (!await AppliedAsync(accountId, split.SourceKey, cancellationToken).ConfigureAwait(false)) + { + return split; + } + } + + return null; + } + + private Task MarketOpenAsync(Instrument instrument, CancellationToken cancellationToken) + { + if (instrument.IsCrypto) + { + return Task.FromResult(true); + } + + if (_market is null) + { + return Task.FromResult(false); + } + + var now = _clock.UtcNow; + var session = _market.UsCalendar.SessionOn(DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(now, NewYork).DateTime)); + return Task.FromResult(session is not null && now >= session.OpenUtc && now < session.CloseUtc); + } + + private static readonly TimeZoneInfo NewYork = TimeZoneInfo.FindSystemTimeZoneById("America/New_York"); + + /// Sets the capital entrusted for a broker and gives the internal simulator the money its ledgers now hold. + public async Task SetCapitalAsync(string broker, decimal amountEur, string changedBy, CancellationToken cancellationToken) + { + var entrusted = await Capital.SetAsync(broker, amountEur, changedBy, cancellationToken).ConfigureAwait(false); + await FundSimulatorsAsync(cancellationToken).ConfigureAwait(false); + return entrusted; + } + + /// + /// The internal simulator's book holds at least the cash its ledgers give the bot: the simulator has no money of + /// its own, it plays the broker for the ledger (SPEC 7.3). + /// + public async Task FundSimulatorsAsync(CancellationToken cancellationToken) + { + var equities = await Ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false); + foreach (var manager in _managers.Values.Where(m => m.Broker is PaperBroker)) + { + var paper = (PaperBroker)manager.Broker; + var mine = equities.Where(e => e.AccountId == manager.Account.AccountId).Sum(e => e.Cash); + var book = await paper.GetAccountAsync(cancellationToken).ConfigureAwait(false); + var there = book.Cash.GetValueOrDefault(manager.Account.Currency); + if (mine > there) + { + await paper.DepositAsync(mine - there, manager.Account.Currency, cancellationToken).ConfigureAwait(false); + } + } + } + + private IBrokerAccount? Build(AccountContext account, AlpacaCredentials? alpaca, OkxCredentials? okx) + { + switch (account.Environment) + { + case TradingEnvironments.Simulation: + var options = account.Broker == Venues.Alpaca ? PaperOptions.Alpaca() : PaperOptions.Okx(account.Currency); + return new PaperBroker(options, _clock, Quotes.GetAsync, symbol => _specs.GetValueOrDefault((account.Broker, symbol)), + new PaperBookStore(_db, _clock, account.AccountId)); + case TradingEnvironments.Demo when account.Broker == Venues.Alpaca && alpaca is not null: + return new AlpacaTrading(_http, _clock, alpaca, new AlpacaTradingOptions { Environment = account.Environment }, _consent, _sockets); + case TradingEnvironments.Demo when account.Broker == Venues.Okx && okx is not null: + return new OkxTrading(_http, _clock, okx, new OkxTradingOptions { Environment = account.Environment, QuoteCurrency = account.Currency }, _consent, _sockets); + default: + // A demo account without keys, or a real account: nothing is sent. + return null; + } + } + + private async Task FollowAsync(OrderManager manager, CancellationToken cancellationToken) + { + var delay = TimeSpan.FromSeconds(1); + while (!cancellationToken.IsCancellationRequested) + { + try + { + await foreach (var update in manager.Broker.StreamOrderUpdatesAsync(cancellationToken).ConfigureAwait(false)) + { + delay = TimeSpan.FromSeconds(1); + await manager.HandleUpdateAsync(update, cancellationToken).ConfigureAwait(false); + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + return; + } + catch (Exception ex) + { + // The periodic query covers the gap (SPEC 7.2): the stream comes back with growing pauses. + LogStreamLost(_logger, manager.Account.Name, Redactor.Redact(ex.Message)); + } + + try + { + await Task.Delay(delay, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + return; + } + + delay = TimeSpan.FromSeconds(Math.Min(delay.TotalSeconds * 2, 60)); + } + } + + private async Task GuardAsync(string what, Func work, CancellationToken cancellationToken) + { + try + { + await work().ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (Exception ex) + { + LogWorkFailed(_logger, ex, what); + } + } + + private async Task RefreshSpecsAsync(CancellationToken cancellationToken) + { + foreach (var instrument in await _catalog.ListAsync(null, cancellationToken).ConfigureAwait(false)) + { + _specs[(instrument.Venue, instrument.Symbol)] = instrument.Spec; + } + } + + private async Task> MinuteBarsAsync(string symbol, DateTimeOffset from, DateTimeOffset to, CancellationToken cancellationToken) + { + var spec = _specs.Values.FirstOrDefault(s => s.Symbol == symbol); + var instrument = spec is null ? null : await _catalog.FindAsync(spec.Venue, symbol, cancellationToken).ConfigureAwait(false); + return instrument is null ? [] : await _bars.MinuteAsync(instrument.Id, from, to, cancellationToken).ConfigureAwait(false); + } + + private async Task FetchQuoteAsync(string symbol, CancellationToken cancellationToken) + { + if (_market is null) + { + return null; + } + + if (symbol.Contains('-', StringComparison.Ordinal)) + { + return await _market.Okx.FetchQuoteAsync(symbol, cancellationToken).ConfigureAwait(false); + } + + var alpaca = await _market.AlpacaAsync(cancellationToken).ConfigureAwait(false); + return alpaca is null ? null : await alpaca.FetchQuoteAsync(symbol, cancellationToken).ConfigureAwait(false); + } + + private async Task AlpacaKeysAsync(CancellationToken cancellationToken) + { + var key = await _secrets.RevealAsync("ALPACA_API_KEY_DEMO", cancellationToken).ConfigureAwait(false); + var secret = await _secrets.RevealAsync("ALPACA_API_SECRET_DEMO", cancellationToken).ConfigureAwait(false); + return string.IsNullOrWhiteSpace(key) || string.IsNullOrWhiteSpace(secret) ? null : new AlpacaCredentials(key, secret); + } + + private async Task OkxKeysAsync(CancellationToken cancellationToken) + { + var key = await _secrets.RevealAsync("OKX_API_KEY_DEMO", cancellationToken).ConfigureAwait(false); + var secret = await _secrets.RevealAsync("OKX_API_SECRET_DEMO", cancellationToken).ConfigureAwait(false); + var passphrase = await _secrets.RevealAsync("OKX_API_PASSPHRASE_DEMO", cancellationToken).ConfigureAwait(false); + return string.IsNullOrWhiteSpace(key) || string.IsNullOrWhiteSpace(secret) || string.IsNullOrWhiteSpace(passphrase) ? null : new OkxCredentials(key, secret, passphrase); + } + + public void Dispose() + { + foreach (var manager in _managers.Values) + { + manager.Dispose(); + (manager.Broker as IDisposable)?.Dispose(); + } + + _http.Dispose(); + } + + [LoggerMessage(Level = LogLevel.Warning, Message = "Order stream of {Account} lost: {Reason}")] + private static partial void LogStreamLost(ILogger logger, string account, string reason); + + [LoggerMessage(Level = LogLevel.Error, Message = "Trading work failed: {What}")] + private static partial void LogWorkFailed(ILogger logger, Exception exception, string what); +} diff --git a/tests/Anubis.Tests/CoreTests.cs b/tests/Anubis.Tests/CoreTests.cs index a538139..a835ac6 100644 --- a/tests/Anubis.Tests/CoreTests.cs +++ b/tests/Anubis.Tests/CoreTests.cs @@ -16,6 +16,15 @@ public sealed class CoreTests Assert.AreEqual(7, first.Version); Assert.IsLessThan(0, string.CompareOrdinal(first.ToString(), second.ToString()), "gli identificativi seguono il tempo"); Assert.AreNotEqual(Ids.NewToken(), Ids.NewToken()); + + // In the same millisecond they still come out in order (two lots of one order, LIFO), with the clock's time. + var burst = Enumerable.Range(0, 5000).Select(_ => Ids.NewId(clock).ToString()).ToList(); + CollectionAssert.AreEqual(burst.Order(StringComparer.Ordinal).ToList(), burst); + Assert.AreEqual(burst.Count, burst.Distinct().Count()); + var time = Convert.ToInt64(burst[0].Replace("-", "", StringComparison.Ordinal)[..12], 16); + Assert.AreEqual(clock.UtcNow.ToUnixTimeMilliseconds(), time); + Assert.AreEqual(7, Guid.Parse(burst[^1]).Version); + Assert.AreEqual(0x8, Guid.Parse(burst[^1]).Variant & 0xC); } [TestMethod] diff --git a/tests/Anubis.Tests/Fixtures/alpaca-trading/account.json b/tests/Anubis.Tests/Fixtures/alpaca-trading/account.json new file mode 100644 index 0000000..bbe3a24 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca-trading/account.json @@ -0,0 +1,39 @@ +{ + "account_blocked": false, + "account_number": "PALPACA_123", + "accrued_fees": "0", + "admin_configurations": {}, + "balance_asof": "2023-09-27", + "buying_power": "245432.61", + "cash": "122086.5", + "created_at": "2023-01-01T18:20:20.272275Z", + "crypto_status": "ACTIVE", + "crypto_tier": 1, + "currency": "USD", + "effective_buying_power": "245432.61", + "equity": "123346.11", + "id": "1d9eed04-be39-4e01-9b84-a48ac5bbafcf", + "initial_margin": "629.8", + "intraday_adjustments": "0", + "last_equity": "122011.09751111286868", + "last_maintenance_margin": "480.73", + "long_market_value": "1259.61", + "maintenance_margin": "377.88", + "multiplier": "2", + "non_marginable_buying_power": "122086.5", + "options_buying_power": "122716.305", + "options_trading_level": 2, + "pending_reg_taf_fees": "0", + "pending_transfer_in": "0", + "portfolio_value": "123346.11", + "position_market_value": "1259.61", + "regt_buying_power": "245432.61", + "short_market_value": "0", + "shorting_enabled": true, + "sma": "123369.74", + "status": "ACTIVE", + "trade_suspended_by_user": false, + "trading_blocked": false, + "transfers_blocked": false, + "user_configurations": null +} diff --git a/tests/Anubis.Tests/Fixtures/alpaca-trading/activity-div.json b/tests/Anubis.Tests/Fixtures/alpaca-trading/activity-div.json new file mode 100644 index 0000000..63edac3 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca-trading/activity-div.json @@ -0,0 +1,10 @@ +{ + "activity_type": "DIV", + "id": "20190801011955195::5f596936-6f23-4cef-bdf1-3806aae57dbf", + "date": "2019-08-01", + "net_amount": "1.02", + "symbol": "T", + "cusip": "C00206R102", + "qty": "2", + "per_share_amount": "0.51" +} diff --git a/tests/Anubis.Tests/Fixtures/alpaca-trading/activity-fill.json b/tests/Anubis.Tests/Fixtures/alpaca-trading/activity-fill.json new file mode 100644 index 0000000..5a91fe8 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca-trading/activity-fill.json @@ -0,0 +1,13 @@ +{ + "activity_type": "FILL", + "cum_qty": "1", + "id": "20190524113406977::8efc7b9a-8b2b-4000-9955-d36e7db0df74", + "leaves_qty": "0", + "price": "1.63", + "qty": "1", + "side": "buy", + "symbol": "LPCN", + "transaction_time": "2019-05-24T15:34:06.977Z", + "order_id": "904837e3-3b76-47ec-b432-046db621571b", + "type": "fill" +} diff --git a/tests/Anubis.Tests/Fixtures/alpaca-trading/error-subpenny.json b/tests/Anubis.Tests/Fixtures/alpaca-trading/error-subpenny.json new file mode 100644 index 0000000..37e645a --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca-trading/error-subpenny.json @@ -0,0 +1,4 @@ +{ + "code": 42210000, + "message": "invalid limit_price 290.123. sub-penny increment does not fulfill minimum pricing criteria" +} diff --git a/tests/Anubis.Tests/Fixtures/alpaca-trading/order-crypto.json b/tests/Anubis.Tests/Fixtures/alpaca-trading/order-crypto.json new file mode 100644 index 0000000..2f11009 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca-trading/order-crypto.json @@ -0,0 +1,36 @@ +{ + "asset_class": "crypto", + "asset_id": "a1733398-6acc-4e92-af24-0d0667f78713", + "canceled_at": null, + "client_order_id": "5b5d3d67-06ad-4ffa-af65-a117d0fc5a59", + "created_at": "2023-12-12T22:36:51.337711497Z", + "expired_at": null, + "extended_hours": false, + "failed_at": null, + "filled_at": null, + "filled_avg_price": null, + "filled_qty": "0", + "hwm": null, + "id": "38e482f3-79a8-4f75-a057-f07a1ec6a397", + "legs": null, + "limit_price": "2100", + "notional": null, + "order_class": "", + "order_type": "limit", + "qty": "0.02", + "replaced_at": null, + "replaced_by": null, + "replaces": null, + "side": "buy", + "source": null, + "status": "pending_new", + "stop_price": null, + "submitted_at": "2023-12-12T22:36:51.313261061Z", + "subtag": null, + "symbol": "ETH/USD", + "time_in_force": "gtc", + "trail_percent": null, + "trail_price": null, + "type": "limit", + "updated_at": "2023-12-12T22:36:51.337754768Z" +} diff --git a/tests/Anubis.Tests/Fixtures/alpaca-trading/order-limit.json b/tests/Anubis.Tests/Fixtures/alpaca-trading/order-limit.json new file mode 100644 index 0000000..3ad706e --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca-trading/order-limit.json @@ -0,0 +1,36 @@ +{ + "asset_class": "us_equity", + "asset_id": "b0b6dd9d-8b9b-48a9-ba46-b9d54906e415", + "canceled_at": null, + "client_order_id": "5680c4bc-9ac1-4a12-a44c-df427ba53032", + "created_at": "2023-12-12T22:31:24.668464435Z", + "expired_at": null, + "extended_hours": false, + "failed_at": null, + "filled_at": null, + "filled_avg_price": null, + "filled_qty": "0", + "hwm": null, + "id": "7b08df51-c1ac-453c-99f9-323a5f075f0d", + "legs": null, + "limit_price": "150", + "notional": null, + "order_class": "", + "order_type": "limit", + "qty": "2", + "replaced_at": null, + "replaced_by": null, + "replaces": null, + "side": "buy", + "source": null, + "status": "accepted", + "stop_price": null, + "submitted_at": "2023-12-12T22:31:24.577215743Z", + "subtag": null, + "symbol": "AAPL", + "time_in_force": "gtc", + "trail_percent": null, + "trail_price": null, + "type": "limit", + "updated_at": "2023-12-12T22:31:24.668464435Z" +} diff --git a/tests/Anubis.Tests/Fixtures/alpaca-trading/position.json b/tests/Anubis.Tests/Fixtures/alpaca-trading/position.json new file mode 100644 index 0000000..47ad991 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca-trading/position.json @@ -0,0 +1,20 @@ +{ + "asset_class": "us_equity", + "asset_id": "904837e3-3b76-47ec-b432-046db621571b", + "asset_marginable": true, + "avg_entry_price": "100.0", + "change_today": "0.0084", + "cost_basis": "500.0", + "current_price": "120.0", + "exchange": "NASDAQ", + "lastday_price": "119.0", + "market_value": "600.0", + "qty": "5", + "qty_available": "4", + "side": "long", + "symbol": "AAPL", + "unrealized_intraday_pl": "10.0", + "unrealized_intraday_plpc": "0.0084", + "unrealized_pl": "100.0", + "unrealized_plpc": "0.20" +} diff --git a/tests/Anubis.Tests/Fixtures/alpaca-trading/ws-authorized.json b/tests/Anubis.Tests/Fixtures/alpaca-trading/ws-authorized.json new file mode 100644 index 0000000..e5f72e7 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca-trading/ws-authorized.json @@ -0,0 +1,7 @@ +{ + "stream": "authorization", + "data": { + "status": "authorized", + "action": "authenticate" + } +} diff --git a/tests/Anubis.Tests/Fixtures/alpaca-trading/ws-fill.json b/tests/Anubis.Tests/Fixtures/alpaca-trading/ws-fill.json new file mode 100644 index 0000000..d875500 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca-trading/ws-fill.json @@ -0,0 +1,46 @@ +{ + "stream": "trade_updates", + "data": { + "event": "fill", + "execution_id": "2f63ea93-423d-4169-b3f6-3fdafc10c418", + "order": { + "asset_class": "crypto", + "asset_id": "1cf35270-99ee-44e2-a77f-6fab902c7f80", + "cancel_requested_at": null, + "canceled_at": null, + "client_order_id": "4642fd68-d59a-47d7-a9ac-e22f536828d1", + "created_at": "2022-04-19T13:45:04.981350886-04:00", + "expired_at": null, + "extended_hours": false, + "failed_at": null, + "filled_at": "2022-04-19T17:45:05.024916716Z", + "filled_avg_price": "105.8988475", + "filled_qty": "1790.86", + "hwm": null, + "id": "a5be8f5e-fdfa-41f5-a644-7a74fe947a8f", + "legs": null, + "limit_price": null, + "notional": null, + "order_class": "", + "order_type": "market", + "qty": "1790.86", + "replaced_at": null, + "replaced_by": null, + "replaces": null, + "side": "sell", + "status": "filled", + "stop_price": null, + "submitted_at": "2022-04-19T13:45:04.980944666-04:00", + "symbol": "SOLUSD", + "time_in_force": "gtc", + "trail_percent": null, + "trail_price": null, + "type": "market", + "updated_at": "2022-04-19T13:45:05.027690731-04:00" + }, + "position_qty": "0", + "price": "105.8988475", + "qty": "1790.86", + "timestamp": "2022-04-19T17:45:05.024916716Z" + } +} diff --git a/tests/Anubis.Tests/Fixtures/alpaca-trading/ws-listening.json b/tests/Anubis.Tests/Fixtures/alpaca-trading/ws-listening.json new file mode 100644 index 0000000..e330533 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/alpaca-trading/ws-listening.json @@ -0,0 +1,6 @@ +{ + "stream": "listening", + "data": { + "streams": ["trade_updates"] + } +} diff --git a/tests/Anubis.Tests/Fixtures/okx-trading/account-config.json b/tests/Anubis.Tests/Fixtures/okx-trading/account-config.json new file mode 100644 index 0000000..a328cbb --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx-trading/account-config.json @@ -0,0 +1,37 @@ +{ + "code": "0", + "data": [ + { + "acctLv": "2", + "acctStpMode": "cancel_maker", + "autoLoan": false, + "ctIsoMode": "automatic", + "enableSpotBorrow": false, + "greeksType": "PA", + "feeType": "0", + "ip": "", + "type": "0", + "kycLv": "3", + "label": "v5 test", + "level": "Lv1", + "levelTmp": "", + "liquidationGear": "-1", + "mainUid": "44705892343619584", + "mgnIsoMode": "automatic", + "opAuth": "1", + "perm": "read_only,withdraw,trade", + "posMode": "long_short_mode", + "roleType": "0", + "spotBorrowAutoRepay": false, + "spotOffsetType": "", + "spotRoleType": "0", + "spotTraderInsts": [], + "stgyType": "0", + "traderInsts": [], + "uid": "44705892343619584", + "settleCcy": "USDC", + "settleCcyList": ["USD", "USDC", "USDG"] + } + ], + "msg": "" +} diff --git a/tests/Anubis.Tests/Fixtures/okx-trading/algo-canceled.json b/tests/Anubis.Tests/Fixtures/okx-trading/algo-canceled.json new file mode 100644 index 0000000..39d9e5a --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx-trading/algo-canceled.json @@ -0,0 +1,14 @@ +{ + "code": "0", + "data": [ + { + "algoClOrdId": "", + "algoId": "1836489397437468672", + "clOrdId": "", + "sCode": "0", + "sMsg": "", + "tag": "" + } + ], + "msg": "" +} diff --git a/tests/Anubis.Tests/Fixtures/okx-trading/algo-placed.json b/tests/Anubis.Tests/Fixtures/okx-trading/algo-placed.json new file mode 100644 index 0000000..661f0ac --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx-trading/algo-placed.json @@ -0,0 +1,14 @@ +{ + "code": "0", + "data": [ + { + "algoClOrdId": "order1234", + "algoId": "1836487817828872192", + "clOrdId": "", + "sCode": "0", + "sMsg": "", + "tag": "" + } + ], + "msg": "" +} diff --git a/tests/Anubis.Tests/Fixtures/okx-trading/algos-pending.json b/tests/Anubis.Tests/Fixtures/okx-trading/algos-pending.json new file mode 100644 index 0000000..9510132 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx-trading/algos-pending.json @@ -0,0 +1,65 @@ +{ + "code": "0", + "data": [ + { + "activePx": "", + "actualPx": "", + "actualSide": "", + "actualSz": "0", + "algoClOrdId": "", + "algoId": "1753184812254216192", + "amendPxOnTriggerType": "0", + "attachAlgoOrds": [], + "cTime": "1724751378980", + "callbackRatio": "", + "callbackSpread": "", + "ccy": "", + "chaseType": "", + "chaseVal": "", + "clOrdId": "", + "closeFraction": "", + "failCode": "0", + "instId": "BTC-USDT", + "instType": "SPOT", + "isTradeBorrowMode": "", + "last": "62916.5", + "lever": "", + "linkedOrd": { + "ordId": "" + }, + "maxChaseType": "", + "maxChaseVal": "", + "moveTriggerPx": "", + "ordId": "", + "ordIdList": [], + "ordPx": "", + "ordType": "conditional", + "posSide": "net", + "pxLimit": "", + "pxSpread": "", + "pxVar": "", + "quickMgnType": "", + "reduceOnly": "false", + "side": "buy", + "slOrdPx": "", + "slTriggerPx": "", + "slTriggerPxType": "", + "state": "live", + "sz": "10", + "szLimit": "", + "tag": "", + "tdMode": "cash", + "tgtCcy": "quote_ccy", + "timeInterval": "", + "tpOrdPx": "-1", + "tpTriggerPx": "10000", + "tpTriggerPxType": "last", + "triggerPx": "", + "triggerPxType": "", + "triggerTime": "", + "tradeQuoteCcy": "USDT", + "uTime": "1724751378980" + } + ], + "msg": "" +} diff --git a/tests/Anubis.Tests/Fixtures/okx-trading/balance.json b/tests/Anubis.Tests/Fixtures/okx-trading/balance.json new file mode 100644 index 0000000..ebebb85 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx-trading/balance.json @@ -0,0 +1,79 @@ +{ + "code": "0", + "data": [ + { + "adjEq": "55415.624719833286", + "availEq": "55415.624719833286", + "borrowFroz": "0", + "delta": "0", + "deltaLever": "0", + "deltaNeutralStatus": "0", + "details": [ + { + "autoLendStatus": "off", + "autoLendMtAmt": "0", + "availBal": "4834.317093622894", + "availEq": "4834.3170936228935", + "borrowFroz": "0", + "cashBal": "4850.435693622894", + "ccy": "USDT", + "crossLiab": "0", + "colRes": "0", + "collateralEnabled": false, + "collateralRestrict": false, + "colBorrAutoConversion": "0", + "disEq": "4991.542013297616", + "eq": "4992.890093622894", + "eqUsd": "4991.542013297616", + "smtSyncEq": "0", + "spotCopyTradingEq": "0", + "fixedBal": "0", + "frozenBal": "158.573", + "frpType": "0", + "imr": "", + "interest": "0", + "isoEq": "0", + "isoLiab": "0", + "isoUpl": "0", + "liab": "0", + "maxLoan": "0", + "mgnRatio": "", + "mmr": "", + "notionalLever": "", + "ordFrozen": "0", + "rewardBal": "0", + "spotInUseAmt": "", + "clSpotInUseAmt": "", + "maxSpotInUse": "", + "spotIsoBal": "0", + "stgyEq": "150", + "twap": "0", + "uTime": "1705449605015", + "upl": "-7.545600000000006", + "uplLiab": "0", + "spotBal": "", + "openAvgPx": "", + "accAvgPx": "", + "spotUpl": "", + "spotUplRatio": "", + "totalPnl": "", + "totalPnlRatio": "" + } + ], + "imr": "0", + "isoEq": "0", + "mgnRatio": "", + "mmr": "0", + "notionalUsd": "0", + "notionalUsdForBorrow": "0", + "notionalUsdForFutures": "0", + "notionalUsdForOption": "0", + "notionalUsdForSwap": "0", + "ordFroz": "", + "totalEq": "55837.43556134779", + "uTime": "1705474164160", + "upl": "0" + } + ], + "msg": "" +} diff --git a/tests/Anubis.Tests/Fixtures/okx-trading/fills.json b/tests/Anubis.Tests/Fixtures/okx-trading/fills.json new file mode 100644 index 0000000..f9d10b9 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx-trading/fills.json @@ -0,0 +1,34 @@ +{ + "code": "0", + "data": [ + { + "side": "buy", + "fillSz": "0.00192834", + "fillPx": "51858", + "fillPxVol": "", + "fillFwdPx": "", + "fee": "-0.00000192834", + "fillPnl": "0", + "ordId": "680800019749904384", + "feeRate": "-0.001", + "instType": "SPOT", + "fillPxUsd": "", + "instId": "BTC-USDT", + "clOrdId": "", + "posSide": "net", + "billId": "680800019754098688", + "subType": "1", + "fillMarkVol": "", + "tag": "", + "fillTime": "1708587373361", + "execType": "T", + "fillIdxPx": "", + "tradeId": "744876980", + "fillMarkPx": "", + "feeCcy": "BTC", + "ts": "1708587373362", + "tradeQuoteCcy": "USDT" + } + ], + "msg": "" +} diff --git a/tests/Anubis.Tests/Fixtures/okx-trading/order-canceled.json b/tests/Anubis.Tests/Fixtures/okx-trading/order-canceled.json new file mode 100644 index 0000000..cfa71c2 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx-trading/order-canceled.json @@ -0,0 +1,15 @@ +{ + "code":"0", + "msg":"", + "data":[ + { + "clOrdId":"oktswap6", + "ordId":"12345689", + "ts":"1695190491421", + "sCode":"0", + "sMsg":"" + } + ], + "inTime": "1695190491421339", + "outTime": "1695190491423240" +} diff --git a/tests/Anubis.Tests/Fixtures/okx-trading/order-failed.json b/tests/Anubis.Tests/Fixtures/okx-trading/order-failed.json new file mode 100644 index 0000000..913ab70 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx-trading/order-failed.json @@ -0,0 +1,18 @@ +{ + "id": "1512", + "op": "order", + "data": [ + { + "clOrdId": "", + "ordId": "", + "tag": "", + "ts":"1695190491421", + "sCode": "5XXXX", + "sMsg": "not exist" + } + ], + "code": "1", + "msg": "", + "inTime": "1695190491421339", + "outTime": "1695190491423240" +} diff --git a/tests/Anubis.Tests/Fixtures/okx-trading/order-filled.json b/tests/Anubis.Tests/Fixtures/okx-trading/order-filled.json new file mode 100644 index 0000000..890e401 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx-trading/order-filled.json @@ -0,0 +1,62 @@ +{ + "code": "0", + "data": [ + { + "accFillSz": "0.00192834", + "algoClOrdId": "", + "algoId": "", + "attachAlgoClOrdId": "", + "attachAlgoOrds": [], + "avgPx": "51858", + "cTime": "1708587373361", + "cancelSource": "", + "cancelSourceReason": "", + "category": "normal", + "ccy": "", + "clOrdId": "", + "fee": "-0.00000192834", + "feeCcy": "BTC", + "fillPx": "51858", + "fillSz": "0.00192834", + "fillTime": "1708587373361", + "instId": "BTC-USDT", + "instType": "SPOT", + "isTpLimit": "false", + "lever": "", + "linkedAlgoOrd": { + "algoId": "" + }, + "ordId": "680800019749904384", + "ordType": "market", + "pnl": "0", + "posSide": "net", + "px": "", + "pxType": "", + "pxUsd": "", + "pxVol": "", + "quickMgnType": "", + "rebate": "0", + "rebateCcy": "USDT", + "reduceOnly": "false", + "side": "buy", + "slOrdPx": "", + "slTriggerPx": "", + "slTriggerPxType": "", + "source": "", + "state": "filled", + "stpId": "", + "stpMode": "", + "sz": "100", + "tag": "", + "tdMode": "cash", + "tgtCcy": "quote_ccy", + "tpOrdPx": "", + "tpTriggerPx": "", + "tpTriggerPxType": "", + "tradeId": "744876980", + "tradeQuoteCcy": "USDT", + "uTime": "1708587373362" + } + ], + "msg": "" +} diff --git a/tests/Anubis.Tests/Fixtures/okx-trading/order-placed.json b/tests/Anubis.Tests/Fixtures/okx-trading/order-placed.json new file mode 100644 index 0000000..d7353bc --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx-trading/order-placed.json @@ -0,0 +1,17 @@ +{ + "code": "0", + "msg": "", + "data": [ + { + "clOrdId": "oktswap6", + "ordId": "312269865356374016", + "tag": "", + "ts":"1695190491421", + "sCode": "0", + "sMsg": "", + "subCode": "" + } + ], + "inTime": "1695190491421339", + "outTime": "1695190491423240" +} diff --git a/tests/Anubis.Tests/Fixtures/okx-trading/orders-pending.json b/tests/Anubis.Tests/Fixtures/okx-trading/orders-pending.json new file mode 100644 index 0000000..828f8ee --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx-trading/orders-pending.json @@ -0,0 +1,62 @@ +{ + "code": "0", + "data": [ + { + "accFillSz": "0", + "algoClOrdId": "", + "algoId": "", + "attachAlgoClOrdId": "", + "attachAlgoOrds": [], + "avgPx": "", + "cTime": "1724733617998", + "cancelSource": "", + "cancelSourceReason": "", + "category": "normal", + "ccy": "", + "clOrdId": "", + "fee": "0", + "feeCcy": "BTC", + "fillPx": "", + "fillSz": "0", + "fillTime": "", + "instId": "BTC-USDT", + "instType": "SPOT", + "isTpLimit": "false", + "lever": "", + "linkedAlgoOrd": { + "algoId": "" + }, + "ordId": "1752588852617379840", + "ordType": "post_only", + "pnl": "0", + "posSide": "net", + "px": "13013.5", + "pxType": "", + "pxUsd": "", + "pxVol": "", + "quickMgnType": "", + "rebate": "0", + "rebateCcy": "USDT", + "reduceOnly": "false", + "side": "buy", + "slOrdPx": "", + "slTriggerPx": "", + "slTriggerPxType": "", + "source": "", + "state": "live", + "stpId": "", + "stpMode": "cancel_maker", + "sz": "0.001", + "tag": "", + "tdMode": "cash", + "tgtCcy": "", + "tpOrdPx": "", + "tpTriggerPx": "", + "tpTriggerPxType": "", + "tradeId": "", + "tradeQuoteCcy": "USDT", + "uTime": "1724733617998" + } + ], + "msg": "" +} diff --git a/tests/Anubis.Tests/Fixtures/okx-trading/trade-fee.json b/tests/Anubis.Tests/Fixtures/okx-trading/trade-fee.json new file mode 100644 index 0000000..06f512d --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx-trading/trade-fee.json @@ -0,0 +1,31 @@ +{ + "code": "0", + "data": [ + { + "category": "1", + "delivery": "", + "exercise": "", + "feeGroup": [ + { + "elpMaker": "-0.0008", + "rpiMaker": "-0.0008", + "groupId": "1", + "maker": "-0.0008", + "taker": "-0.001" + } + ], + "fiat": [], + "instType": "SPOT", + "level": "Lv1", + "maker": "-0.0008", + "makerU": "", + "makerUSDC": "", + "ruleType": "normal", + "taker": "-0.001", + "takerU": "", + "takerUSDC": "", + "ts": "1763979985847" + } + ], + "msg": "" +} diff --git a/tests/Anubis.Tests/Fixtures/okx-trading/ws-algo-live.json b/tests/Anubis.Tests/Fixtures/okx-trading/ws-algo-live.json new file mode 100644 index 0000000..cedc793 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx-trading/ws-algo-live.json @@ -0,0 +1,56 @@ +{ + "arg": { + "channel": "orders-algo", + "uid": "77982378738415879", + "instType": "FUTURES", + "instId": "BTC-USD-200329" + }, + "data": [{ + "actualPx": "0", + "actualSide": "", + "actualSz": "0", + "algoClOrdId": "", + "algoId": "581878926302093312", + "attachAlgoOrds": [], + "amendResult": "", + "cTime": "1685002746818", + "uTime": "1708679675245", + "ccy": "", + "clOrdId": "", + "closeFraction": "", + "failCode": "", + "instId": "BTC-USDC", + "instType": "SPOT", + "last": "26174.8", + "lever": "0", + "notionalUsd": "11.0", + "ordId": "", + "ordIdList": [], + "ordPx": "", + "ordType": "conditional", + "posSide": "", + "quickMgnType": "", + "reduceOnly": "false", + "reqId": "", + "side": "buy", + "slOrdPx": "", + "slTriggerPx": "", + "slTriggerPxType": "", + "state": "live", + "sz": "11", + "tag": "", + "tdMode": "cross", + "tgtCcy": "quote_ccy", + "tpOrdPx": "-1", + "tpTriggerPx": "1", + "tpTriggerPxType": "last", + "triggerPx": "", + "triggerTime": "", + "tradeQuoteCcy": "USDT", + "amendPxOnTriggerType": "0", + "linkedOrd":{ + "ordId":"98192973880283" + }, + "isTradeBorrowMode": "" + }] +} diff --git a/tests/Anubis.Tests/Fixtures/okx-trading/ws-login.json b/tests/Anubis.Tests/Fixtures/okx-trading/ws-login.json new file mode 100644 index 0000000..5462c12 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx-trading/ws-login.json @@ -0,0 +1,6 @@ +{ + "event": "login", + "code": "0", + "msg": "", + "connId": "a4d3ae55" +} diff --git a/tests/Anubis.Tests/Fixtures/okx-trading/ws-order-filled.json b/tests/Anubis.Tests/Fixtures/okx-trading/ws-order-filled.json new file mode 100644 index 0000000..7a83257 --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx-trading/ws-order-filled.json @@ -0,0 +1,84 @@ +{ + "arg": { + "channel": "orders", + "instType": "SPOT", + "instId": "BTC-USDT", + "uid": "614488474791936" + }, + "data": [ + { + "accFillSz": "0.001", + "algoClOrdId": "", + "algoId": "", + "amendResult": "", + "amendSource": "", + "avgPx": "31527.1", + "cancelSource": "", + "category": "normal", + "ccy": "", + "clOrdId": "", + "code": "0", + "cTime": "1654084334977", + "execType": "M", + "fee": "-0.02522168", + "feeCcy": "USDT", + "fillFee": "-0.02522168", + "fillFeeCcy": "USDT", + "fillNotionalUsd": "31.50818374", + "fillPx": "31527.1", + "fillSz": "0.001", + "fillPnl": "0.01", + "fillTime": "1654084353263", + "fillPxVol": "", + "fillPxUsd": "", + "fillMarkVol": "", + "fillFwdPx": "", + "fillMarkPx": "", + "fillIdxPx": "", + "instId": "BTC-USDT", + "instType": "SPOT", + "lever": "0", + "msg": "", + "notionalUsd": "31.50818374", + "ordId": "452197707845865472", + "ordType": "limit", + "pnl": "0", + "posSide": "", + "px": "31527.1", + "pxUsd":"", + "pxVol":"", + "pxType":"", + "quickMgnType": "", + "rebate": "0", + "rebateCcy": "BTC", + "reduceOnly": "false", + "reqId": "", + "side": "sell", + "attachAlgoClOrdId": "", + "slOrdPx": "", + "slTriggerPx": "", + "slTriggerPxType": "last", + "source": "", + "state": "filled", + "stpId": "", + "stpMode": "", + "sz": "0.001", + "tag": "", + "tdMode": "cash", + "tgtCcy": "", + "tpOrdPx": "", + "tpTriggerPx": "", + "tpTriggerPxType": "last", + "attachAlgoOrds": [], + "tradeId": "242589207", + "tradeQuoteCcy": "USDT", + "lastPx": "38892.2", + "uTime": "1654084353264", + "isTpLimit": "false", + "riskBypassResult": "", + "linkedAlgoOrd": { + "algoId": "" + } + } + ] +} diff --git a/tests/Anubis.Tests/Fixtures/okx-trading/ws-subscribed.json b/tests/Anubis.Tests/Fixtures/okx-trading/ws-subscribed.json new file mode 100644 index 0000000..175f2ad --- /dev/null +++ b/tests/Anubis.Tests/Fixtures/okx-trading/ws-subscribed.json @@ -0,0 +1,10 @@ +{ + "id": "1512", + "event": "subscribe", + "arg": { + "channel": "orders", + "instType": "FUTURES", + "instId": "BTC-USD-200329" + }, + "connId": "a4d3ae55" +} diff --git a/tests/Anubis.Tests/LedgerTests.cs b/tests/Anubis.Tests/LedgerTests.cs new file mode 100644 index 0000000..0106cf5 --- /dev/null +++ b/tests/Anubis.Tests/LedgerTests.cs @@ -0,0 +1,262 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// The bot's books (issue #29, SPEC 7.5): append-only rows, lots, trades from zero to zero, equity, returns. +[TestClass] +public sealed class LedgerTests +{ + private static readonly CancellationToken _none = CancellationToken.None; + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task BuyAndSellMakeATradeFromZeroToZeroWithFeesAndResult() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var account = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Simulation).ConfigureAwait(false); + var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")).ConfigureAwait(false); + const string strategy = Strategies.EquityMomentum; + await rig.Ledger.RecordCapitalAsync(account.AccountId, strategy, 10000m, "USD", "test", _none).ConfigureAwait(false); + + var first = await rig.Ledger.RecordFillAsync(rig.Fill(account, msft, strategy, OrderSide.Buy, 10m, 400m, 0.03m) with { ReferencePrice = 399.8m }, _none).ConfigureAwait(false); + Assert.IsTrue(first.Recorded); + Assert.AreEqual(10m, first.Quantity); + Assert.AreEqual(400.003m, first.AveragePrice, "The fee is part of the cost."); + Assert.AreEqual(Math.Round(0.2m / 399.8m * 10000m, 6), Math.Round(first.SlippageBp!.Value, 6), "Slippage against the reference, in basis points."); + await rig.Ledger.RecordFillAsync(rig.Fill(account, msft, strategy, OrderSide.Buy, 5m, 412m), _none).ConfigureAwait(false); + + // A partial sale enters the realised result at once; the trade stays open. + var partial = await rig.Ledger.RecordFillAsync(rig.Fill(account, msft, strategy, OrderSide.Sell, 6m, 420m, 0.06m), _none).ConfigureAwait(false); + Assert.AreEqual(9m, partial.Quantity); + Assert.IsFalse(partial.TradeClosed); + var last = await rig.Ledger.RecordFillAsync(rig.Fill(account, msft, strategy, OrderSide.Sell, 9m, 430m, 0.09m) with { ExitReason = "stop" }, _none).ConfigureAwait(false); + Assert.IsTrue(last.TradeClosed); + Assert.AreEqual(0m, last.Quantity); + Assert.IsNull(await rig.Ledger.PositionAsync(account.AccountId, msft.Id, strategy, _none).ConfigureAwait(false), "A closed position is gone."); + + var trade = (await rig.QueryAsync("SELECT status, bought_quantity, sold_quantity, fees, realized, exit_reason FROM trades", + r => (Status: r.Text("status"), Bought: r.Money("bought_quantity"), Sold: r.Money("sold_quantity"), Fees: r.Money("fees"), Realized: r.Money("realized"), Exit: r.TextOrNull("exit_reason"))) + .ConfigureAwait(false)).Single(); + Assert.AreEqual(("closed", 15m, 15m, 0.18m, "stop"), (trade.Status, trade.Bought, trade.Sold, trade.Fees, trade.Exit)); + + // Net result: money in minus money out, fees included. + var expected = (6m * 420m) + (9m * 430m) - (10m * 400m) - (5m * 412m) - 0.18m; + Assert.AreEqual(expected, trade.Realized); + var equity = (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(); + Assert.AreEqual(10000m + expected, equity.Equity); + Assert.AreEqual(expected, equity.Result); + + // The same execution twice is recorded once (duplicate fills, SPEC 7.4). + var fill = rig.Fill(account, msft, strategy, OrderSide.Buy, 1m, 400m); + Assert.IsTrue((await rig.Ledger.RecordFillAsync(fill, _none).ConfigureAwait(false)).Recorded); + Assert.IsFalse((await rig.Ledger.RecordFillAsync(fill, _none).ConfigureAwait(false)).Recorded); + Assert.AreEqual(1m, (await rig.Ledger.PositionAsync(account.AccountId, msft.Id, strategy, _none).ConfigureAwait(false))!.Quantity); + + // Never sells what the strategy does not hold. + await Assert.ThrowsExactlyAsync(() => rig.Ledger.RecordFillAsync(rig.Fill(account, msft, strategy, OrderSide.Sell, 2m, 400m), _none)).ConfigureAwait(false); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task FeesTakenInTheCoinReduceTheQuantityAndLotsFollowTheTaxMethod() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); + var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); + const string strategy = Strategies.CryptoTrend; + await rig.Ledger.RecordCapitalAsync(account.AccountId, strategy, 5000m, "EUR", "test", _none).ConfigureAwait(false); + + // OKX keeps the fee of a purchase in the bought coin (SPEC 4.2): 0.01 bought, 0.00001 kept. + var buy = await rig.Ledger.RecordFillAsync(rig.Fill(account, btc, strategy, OrderSide.Buy, 0.01m, 60000m, 0.00001m, "BTC"), _none).ConfigureAwait(false); + Assert.AreEqual(0.00999m, buy.Quantity); + Assert.AreEqual(Math.Round(600m / 0.00999m, 10), Math.Round(buy.AveragePrice, 10)); + await rig.Ledger.RecordFillAsync(rig.Fill(account, btc, strategy, OrderSide.Buy, 0.01m, 62000m, 0.00001m, "BTC"), _none).ConfigureAwait(false); + + // LIFO (default): the newest lot leaves first. + await rig.Ledger.RecordFillAsync(rig.Fill(account, btc, strategy, OrderSide.Sell, 0.005m, 63000m, 0.63m, "EUR"), _none).ConfigureAwait(false); + var lots = await rig.Ledger.OpenLotsAsync(account.AccountId, btc.Id, strategy, _none).ConfigureAwait(false); + Assert.HasCount(2, lots); + Assert.AreEqual(0.00499m, lots.Single(l => l.Price > 61000m).Remaining); + Assert.AreEqual(0.00999m, lots.Single(l => l.Price < 61000m).Remaining); + + var fifo = new Ledger(rig.Db, rig.Clock) { LotMethod = LotMethod.Fifo }; + var ordered = await fifo.OpenLotsAsync(account.AccountId, btc.Id, strategy, _none).ConfigureAwait(false); + Assert.IsLessThan(ordered[1].Price, ordered[0].Price, "FIFO lists the oldest lot first."); + + var position = await rig.Ledger.PositionAsync(account.AccountId, btc.Id, strategy, _none).ConfigureAwait(false); + Assert.AreEqual(0.01498m, position!.Quantity); + Assert.AreEqual(position.Quantity, lots.Sum(l => l.Remaining), "Lots and position always agree."); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task ResiduesDividendsSplitsAndReversalsKeepTheBooksRight() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var okx = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); + var alpaca = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Simulation).ConfigureAwait(false); + var pepe = await rig.InstrumentAsync(TradingRig.Pepe).ConfigureAwait(false); + var aapl = await rig.InstrumentAsync(TradingRig.Stock("AAPL")).ConfigureAwait(false); + await rig.Ledger.RecordCapitalAsync(okx.AccountId, Strategies.CryptoTrend, 1000m, "EUR", "test", _none).ConfigureAwait(false); + await rig.Ledger.RecordCapitalAsync(alpaca.AccountId, Strategies.EquityMomentum, 3000m, "USD", "test", _none).ConfigureAwait(false); + + // A residue below the minimum is written off at market value as a cost: the trade closes (SPEC 7.2). + await rig.Ledger.RecordFillAsync(rig.Fill(okx, pepe, Strategies.CryptoTrend, OrderSide.Buy, 10_000_000m, 0.00001m), _none).ConfigureAwait(false); + await rig.Ledger.RecordFillAsync(rig.Fill(okx, pepe, Strategies.CryptoTrend, OrderSide.Sell, 9_950_000m, 0.000011m), _none).ConfigureAwait(false); + await rig.Ledger.WriteOffResidueAsync(okx.AccountId, pepe.Id, Strategies.CryptoTrend, 0.000011m, "below_minimum", _none).ConfigureAwait(false); + Assert.IsNull(await rig.Ledger.PositionAsync(okx.AccountId, pepe.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false)); + var residue = (await rig.QueryAsync("SELECT quantity, value FROM residues", r => (Q: r.Money("quantity"), V: r.Money("value"))).ConfigureAwait(false)).Single(); + Assert.AreEqual((50_000m, 0.55m), (residue.Q, residue.V)); + var trade = (await rig.QueryAsync("SELECT status, realized FROM trades WHERE instrument_id = @i", r => (S: r.Text("status"), R: r.Money("realized")), ("i", pepe.Id)) + .ConfigureAwait(false)).Single(); + Assert.AreEqual("closed", trade.S); + var okxEquity = (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(e => e.AccountId == okx.AccountId); + Assert.AreEqual(okxEquity.Result, trade.R, "The written-off value is a loss of the trade, nothing else."); + + // A dividend goes to whoever held the stock before the ex-date. + await rig.Ledger.RecordFillAsync(rig.Fill(alpaca, aapl, Strategies.EquityMomentum, OrderSide.Buy, 10m, 200m), _none).ConfigureAwait(false); + rig.Clock.Advance(TimeSpan.FromDays(3)); + Assert.AreEqual(10m, await rig.Ledger.QuantityAtAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, rig.Clock.UtcNow, _none).ConfigureAwait(false)); + Assert.AreEqual(0m, await rig.Ledger.QuantityAtAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, TradingRig.Start.AddMinutes(-1), _none).ConfigureAwait(false)); + await rig.Ledger.RecordDividendAsync(alpaca.AccountId, Strategies.EquityMomentum, 2.5m, "USD", rig.Clock.UtcNow, "Dividendo AAPL", _none).ConfigureAwait(false); + + // A 4-for-1 split: four times the shares at a quarter of the price, the value unchanged; applied once. + await rig.Ledger.SetStopAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, 180m, _none).ConfigureAwait(false); + var before = (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(e => e.AccountId == alpaca.AccountId); + Assert.IsTrue(await rig.Ledger.ApplySplitAsync(alpaca.AccountId, aapl.Id, "split-aapl-1", 4m, _none).ConfigureAwait(false)); + Assert.IsFalse(await rig.Ledger.ApplySplitAsync(alpaca.AccountId, aapl.Id, "split-aapl-1", 4m, _none).ConfigureAwait(false), "Never twice."); + var split = (await rig.Ledger.PositionAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!; + Assert.AreEqual((40m, 50m, 45m), (split.Quantity, split.AveragePrice, split.StopPrice)); + Assert.AreEqual(40m, (await rig.Ledger.OpenLotsAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false)).Sum(l => l.Remaining)); + var after = (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(e => e.AccountId == alpaca.AccountId); + Assert.AreEqual(before.Equity, after.Equity); + Assert.AreEqual(3002.5m, after.Equity, "Capital, plus the dividend; the position at its own price."); + + // A cash row is never changed: it is reversed by an opposite row that points at it. + var dividend = (await rig.QueryAsync("SELECT id FROM cash_ledger WHERE kind = 'dividend'", r => r.Id("id")).ConfigureAwait(false)).Single(); + await rig.Ledger.ReverseCashAsync(dividend, "Dividendo registrato due volte", _none).ConfigureAwait(false); + Assert.AreEqual(3000m, (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(e => e.AccountId == alpaca.AccountId).Equity); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task RandomFillsNeverBreakTheBooks() + { + // Fixed seed (SPEC 18): cash + positions = equity, no negative quantity, lots = position, result = realised + unrealised. + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); + var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); + var eth = await rig.InstrumentAsync(MarketDataStoreTests.Okx("ETH-EUR")).ConfigureAwait(false); + const string strategy = Strategies.CryptoTrend; + await rig.Ledger.RecordCapitalAsync(account.AccountId, strategy, 100_000m, "EUR", "test", _none).ConfigureAwait(false); + + var gen = new Gen(Property.DefaultSeed); + var prices = new Dictionary { [btc.Id] = 60000m, [eth.Id] = 3000m }; + for (var step = 0; step < 60; step++) + { + var instrument = gen.Bool() ? btc : eth; + prices[instrument.Id] = Math.Round(prices[instrument.Id] * (1m + gen.Decimal(-0.03m, 0.03m, 4)), 2); + var price = prices[instrument.Id]; + var held = (await rig.Ledger.PositionAsync(account.AccountId, instrument.Id, strategy, _none).ConfigureAwait(false))?.Quantity ?? 0m; + var buy = held == 0m || gen.Int(0, 3) > 0; + var inKind = gen.Bool(); + rig.Clock.Advance(TimeSpan.FromMinutes(7)); + if (buy) + { + var quantity = gen.Decimal(0.001m, 0.05m, 5); + var fee = inKind ? Math.Round(quantity * 0.001m, 8) : Math.Round(quantity * price * 0.002m, 2); + await rig.Ledger.RecordFillAsync(rig.Fill(account, instrument, strategy, OrderSide.Buy, quantity, price, fee, inKind ? instrument.Spec.BaseCurrency : "EUR"), _none) + .ConfigureAwait(false); + } + else + { + var quantity = gen.Int(0, 4) == 0 ? held : Math.Round(held * gen.Decimal(0.1m, 0.9m, 2), 8); + await rig.Ledger.RecordFillAsync(rig.Fill(account, instrument, strategy, OrderSide.Sell, quantity, price, Math.Round(quantity * price * 0.002m, 2)), _none) + .ConfigureAwait(false); + } + + await rig.Ledger.MarkAsync(instrument.Id, price, _none).ConfigureAwait(false); + await AssertBooksAsync(rig, account, strategy, step).ConfigureAwait(false); + } + } + + private static async Task AssertBooksAsync(TradingRig rig, AccountContext account, string strategy, int step) + { + var positions = await rig.Ledger.PositionsAsync(account.AccountId, _none).ConfigureAwait(false); + var cash = (await rig.QueryAsync("SELECT amount FROM cash_ledger WHERE account_id = @a AND currency = 'EUR'", r => r.Money("amount"), ("a", account.AccountId)).ConfigureAwait(false)).Sum(); + var equity = (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(); + Assert.AreEqual(cash + positions.Sum(p => p.Value), equity.Equity, 0.000001m, $"passo {step}: liquidità + posizioni = patrimonio"); + Assert.IsTrue(positions.All(p => p.Quantity > 0m), $"passo {step}: nessuna quantità negativa"); + foreach (var position in positions) + { + var lots = (await rig.Ledger.OpenLotsAsync(account.AccountId, position.InstrumentId, strategy, _none).ConfigureAwait(false)).Sum(l => l.Remaining); + Assert.AreEqual(position.Quantity, lots, 0.000000001m, $"passo {step}: lotti = posizione"); + } + + var realized = (await rig.QueryAsync("SELECT realized FROM trades", r => r.Money("realized")).ConfigureAwait(false)).Sum(); + Assert.AreEqual(realized + positions.Sum(p => p.Unrealized), equity.Result, 0.0001m, $"passo {step}: risultato = realizzato + non realizzato"); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task EquityPhotographsSeparateWorldsAndCorrectForCapitalChanges() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var fx = new FxStore(rig.Db, rig.Clock); + await fx.UpsertAsync([new FxRate("EUR", "USD", new DateOnly(2026, 11, 9), 1.10m, "ecb")], _none).ConfigureAwait(false); + var okx = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); + var alpaca = await rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Demo).ConfigureAwait(false); + await rig.Db.WriteAsync(async s => + { + foreach (var (strategy, account, share) in new[] { (Strategies.CryptoTrend, okx, 1m), (Strategies.EquityMomentum, alpaca, 0.75m), (Strategies.EquityMeanrev, alpaca, 0.25m) }) + { + await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share) VALUES (@id, @s, @a, 'observation', 0, @j, @now, @now, @sh)", + _none, ("id", Ids.NewId(rig.Clock)), ("s", strategy), ("a", account.AccountId), ("j", new Anubis.Db.DbJson("{}")), ("now", rig.Clock.UtcNow), ("sh", share)) + .ConfigureAwait(false); + } + }, _none).ConfigureAwait(false); + + // 4,000 € on OKX all to crypto_trend; 6,000 € on Alpaca at 1.10 $/€ = 6,600 $, 75/25 (SPEC 8.6). + var capital = new Capital(rig.Db, rig.Clock, rig.Ledger, fx); + await capital.SetAsync(Venues.Okx, 4000m, "test", _none).ConfigureAwait(false); + var alpacaCapital = await capital.SetAsync(Venues.Alpaca, 6000m, "test", _none).ConfigureAwait(false); + Assert.AreEqual(6600m, alpacaCapital.Amount); + var strategies = await capital.StrategiesAsync(Venues.Alpaca, _none).ConfigureAwait(false); + Assert.AreEqual(4950m, strategies.Single(s => s.Strategy == Strategies.EquityMomentum).Capital); + Assert.AreEqual(1650m, strategies.Single(s => s.Strategy == Strategies.EquityMeanrev).Capital); + + var book = new EquityBook(rig.Db, rig.Clock, rig.Ledger, fx); + await book.TakeAsync(_none).ConfigureAwait(false); + + // A gain of 400 € on OKX, then the capital doubles: the return stays 10%, the deposit is no gain. + var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); + await rig.Ledger.RecordFillAsync(rig.Fill(okx, btc, Strategies.CryptoTrend, OrderSide.Buy, 0.05m, 60000m), _none).ConfigureAwait(false); + await rig.Ledger.MarkAsync(btc.Id, 68000m, _none).ConfigureAwait(false); + rig.Clock.Advance(TimeSpan.FromMinutes(5)); + await book.TakeAsync(_none).ConfigureAwait(false); + await capital.SetAsync(Venues.Okx, 8000m, "test", _none).ConfigureAwait(false); + rig.Clock.Advance(TimeSpan.FromMinutes(5)); + await book.TakeAsync(_none).ConfigureAwait(false); + + var series = await rig.QueryAsync("SELECT equity, flows, twr_index, drawdown_pct FROM equity_snapshots WHERE scope = 'strategy' AND strategy = @s ORDER BY taken_at", + r => (E: r.Money("equity"), F: r.Money("flows"), I: r.Money("twr_index"), D: r.Money("drawdown_pct")), ("s", Strategies.CryptoTrend)).ConfigureAwait(false); + CollectionAssert.AreEqual(new[] { 4000m, 4400m, 8400m }, series.Select(p => p.E).ToArray()); + Assert.AreEqual(1.1m, series[^1].I); + Assert.AreEqual(0.1m, Returns.TimeWeighted(series.Select(p => (p.E, p.F)).ToList())); + + // Simulated money (OKX in the simulator) and demo money are both "simulated": real money is a world apart. + var totals = await rig.QueryAsync("SELECT world, currency, equity, fx_effect FROM equity_snapshots WHERE scope = 'total' ORDER BY taken_at DESC", + r => (W: r.Text("world"), C: r.Text("currency"), E: r.Money("equity"), Fx: r.MoneyOrNull("fx_effect"))).ConfigureAwait(false); + Assert.IsTrue(totals.All(t => t.W == Worlds.Simulated && t.C == "EUR")); + Assert.AreEqual(8400m + 6000m, totals[0].E, "The total in euro: 6,600 $ at 1.10 is 6,000 €."); + Assert.AreEqual(0m, totals[0].Fx, "Same rate as the day of the capital: no FX effect."); + + // Reducing capital below what is invested is refused: the bot never sells to give money back. + var error = await Assert.ThrowsExactlyAsync(() => capital.SetAsync(Venues.Okx, 0m, "test", _none)).ConfigureAwait(false); + Assert.Contains("crypto_trend", error.Message); + await Assert.ThrowsExactlyAsync(() => + capital.SetSharesAsync(Venues.Alpaca, new Dictionary { [Strategies.EquityMomentum] = 0.8m, [Strategies.EquityMeanrev] = 0.3m }, "test", _none)).ConfigureAwait(false); + } +} diff --git a/tests/Anubis.Tests/TradingRulesTests.cs b/tests/Anubis.Tests/TradingRulesTests.cs new file mode 100644 index 0000000..cf4e6ea --- /dev/null +++ b/tests/Anubis.Tests/TradingRulesTests.cs @@ -0,0 +1,163 @@ +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, Strategies.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, Strategies.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, Strategies.EquityMomentum, OrderPurpose.Stop, key, 1298)); + Assert.ThrowsExactly(() => + ClientOrderIds.Build(installation, TradingEnvironments.Demo, Strategies.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); + + 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 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."); + } +} diff --git a/tests/Anubis.Tests/TradingSupport.cs b/tests/Anubis.Tests/TradingSupport.cs new file mode 100644 index 0000000..255e124 --- /dev/null +++ b/tests/Anubis.Tests/TradingSupport.cs @@ -0,0 +1,130 @@ +using System.Collections.Concurrent; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// +/// A migrated database on the engine of this run with what trading tests need: a manual clock, quotes set by the +/// test, accounts and instruments, the internal simulator and order managers. Tuesday 10 November 2026, 10:00 in New York. +/// +internal sealed class TradingRig : IAsyncDisposable +{ + public const string Installation = "TST1"; + + public static readonly DateTimeOffset Start = new(2026, 11, 10, 15, 0, 0, TimeSpan.Zero); + + private readonly ConcurrentDictionary _quotes = new(StringComparer.Ordinal); + private readonly ConcurrentDictionary _specs = new(StringComparer.Ordinal); + private readonly ConcurrentDictionary _instruments = new(); + private readonly List _owned = []; + + private TradingRig(TestDb test) + { + Test = test; + Clock = new ManualClock(Start); + Ledger = new Ledger(test.Db, Clock); + Catalog = new InstrumentCatalog(test.Db, Clock); + } + + public TestDb Test { get; } + + public Database Db => Test.Db; + + public ManualClock Clock { get; } + + public Ledger Ledger { get; } + + public InstrumentCatalog Catalog { get; } + + /// Quotes are refused while this is true: the price feed is "down". + public bool QuotesDown { get; set; } + + public static async Task CreateAsync() => new(await DatabaseTests.MigratedAsync().ConfigureAwait(false)); + + public async Task AccountAsync(string broker, string environment, string? name = null) + { + var account = new AccountContext(Ids.NewId(Clock), name ?? AccountSetup.NameOf(broker, environment), broker, environment, Strategies.CurrencyOf(broker)); + await Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, @n, @b, @e, @c, @now)", CancellationToken.None, + ("id", account.AccountId), ("n", account.Name), ("b", broker), ("e", environment), ("c", account.Currency), ("now", Clock.UtcNow)), CancellationToken.None).ConfigureAwait(false); + return account; + } + + public async Task InstrumentAsync(InstrumentSpec spec) + { + var instrument = await Catalog.EnsureAsync(spec, CancellationToken.None).ConfigureAwait(false); + _specs[spec.Symbol] = instrument.Spec; + _instruments[instrument.Id] = instrument; + return instrument; + } + + public static InstrumentSpec Btc => MarketDataStoreTests.Okx("BTC-EUR") with { TickSize = 0.1m, LotSize = 0.00000001m, MinSize = 0.00001m }; + + public static InstrumentSpec Pepe => MarketDataStoreTests.Okx("PEPE-EUR") with { TickSize = 0.00000001m, LotSize = 1m, MinSize = 100000m }; + + public static InstrumentSpec Stock(string symbol, bool fractionable = true) => TradingRulesTests.Stock(symbol, fractionable); + + public void Quote(string symbol, decimal bid, decimal ask, decimal? size = null) => + _quotes[symbol] = new Quote(symbol, bid, ask, Clock.UtcNow) { BidSize = size, AskSize = size }; + + public Task QuoteAsync(string symbol, CancellationToken cancellationToken) => + Task.FromResult(QuotesDown ? null : _quotes.TryGetValue(symbol, out var quote) ? quote : null); + + public Task FindAsync(Guid id, CancellationToken cancellationToken) => Task.FromResult(_instruments.GetValueOrDefault(id)); + + public InstrumentSpec? Spec(string symbol) => _specs.GetValueOrDefault(symbol); + + public PaperBroker Paper(PaperOptions options, Guid accountId, bool persist = true) + { + var broker = new PaperBroker(options with { MinLatency = TimeSpan.Zero, MaxLatency = TimeSpan.Zero }, Clock, QuoteAsync, Spec, + persist ? new PaperBookStore(Db, Clock, accountId) : null); + _owned.Add(broker); + return broker; + } + + public OrderManager Manager(IBrokerAccount broker, AccountContext account, Func>? marketOpen = null, + Func>? pendingSplit = null) + { + var manager = new OrderManager(Db, Clock, Ledger, broker, account, Installation, FindAsync, QuoteAsync) + { + ConfirmPrice = QuoteAsync, + MarketOpen = marketOpen ?? ((_, _) => Task.FromResult(true)), + PendingSplit = pendingSplit, + }; + _owned.Add(manager); + return manager; + } + + /// Several turns of the order manager, the clock moving between them (the simulator's latency, the steps). + public async Task TurnsAsync(OrderManager manager, int turns, TimeSpan every) + { + for (var i = 0; i < turns; i++) + { + if (manager.Broker is PaperBroker paper) + { + await paper.PumpAsync(CancellationToken.None).ConfigureAwait(false); + } + + await manager.TickAsync(CancellationToken.None).ConfigureAwait(false); + Clock.Advance(every); + } + } + + public Task> QueryAsync(string sql, Func read, params (string, object?)[] args) => + Db.ReadAsync>(async s => await s.QueryAsync(sql, read, args).ConfigureAwait(false), CancellationToken.None); + + public LedgerFill Fill(AccountContext account, Instrument instrument, string strategy, OrderSide side, decimal quantity, decimal price, decimal fee = 0m, string? feeCurrency = null) => + new(account.AccountId, instrument.Id, strategy, "X" + Ids.NewId(Clock).ToString("N"), side, quantity, price, fee, feeCurrency ?? instrument.Spec.QuoteCurrency, Clock.UtcNow); + + public async ValueTask DisposeAsync() + { + foreach (var owned in _owned) + { + owned.Dispose(); + } + + await Test.DisposeAsync().ConfigureAwait(false); + } +} -- 2.54.1 From e3caa2620747a33db58239681769aa4aceb4891f Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 10 Nov 2026 20:40:21 +0100 Subject: [PATCH 2/7] Test the order manager and reconciliation end to end (refs #27 #28 #30) Order manager tests drive the internal simulator turn by turn: the chasing limit with its post-only steps and aggressive cross, a buy given up, a sale never given up with its alert, the pace of six sends a minute, Alpaca's GTC + day stops, the stop-already-passed rule and splits, lost answers, duplicate fills, refusals and residues. Reconciliation tests cover clean, healed, prudent mode and its return, align/exclude, unknown orders, stop coverage, withdraw-capable keys and an unreachable broker. Two defects found by the tests are fixed: stops were not cleared before an execution that starts aggressive (Alpaca refuses a buy with a sell stop open, and a sale must free the quantity), and an order's creation is now recorded as its first event. Co-Authored-By: Claude Opus 5.5 --- src/Anubis/Trading/OrderManager.cs | 28 ++- tests/Anubis.Tests/OrderManagerTests.cs | 314 ++++++++++++++++++++++++ tests/Anubis.Tests/PaperBrokerTests.cs | 158 ++++++++++++ tests/Anubis.Tests/ReconcilerTests.cs | 219 +++++++++++++++++ tests/Anubis.Tests/TradingSupport.cs | 100 ++++++++ 5 files changed, 813 insertions(+), 6 deletions(-) create mode 100644 tests/Anubis.Tests/OrderManagerTests.cs create mode 100644 tests/Anubis.Tests/PaperBrokerTests.cs create mode 100644 tests/Anubis.Tests/ReconcilerTests.cs diff --git a/src/Anubis/Trading/OrderManager.cs b/src/Anubis/Trading/OrderManager.cs index 8a93f2f..c9410c8 100644 --- a/src/Anubis/Trading/OrderManager.cs +++ b/src/Anubis/Trading/OrderManager.cs @@ -339,12 +339,19 @@ public sealed partial class OrderManager : IDisposable return null; } - if (current.Kind != OrderKind.Market && exec.StepStartedAt is { } started && _clock.UtcNow - started >= StepTime) + if (current.Kind == OrderKind.Market || exec.StepStartedAt is not { } started || _clock.UtcNow - started < StepTime) { - await CancelAndReadAsync(current, instrument, "step time over", cancellationToken).ConfigureAwait(false); + return null; } - return null; + // The step's time is over: the next step leaves in this same turn, but only once the broker confirms + // the cancellation, and only for what is left (SPEC 7.2). + await CancelAndReadAsync(current, instrument, "step time over", cancellationToken).ConfigureAwait(false); + orders = await ExecutionOrdersAsync(exec.Id, cancellationToken).ConfigureAwait(false); + if (orders.LastOrDefault() is not { } after || !OrderStates.IsFinal(after.Status)) + { + return null; + } } var filled = orders.Sum(o => o.Filled); @@ -373,13 +380,13 @@ public sealed partial class OrderManager : IDisposable return null; } - if (exec.Side == OrderSide.Sell && exec.Step < 0 && !await ClearStopsCoreAsync(exec.InstrumentId, exec.Strategy, instrument, cancellationToken).ConfigureAwait(false)) + if (exec.Side == OrderSide.Sell && exec.Sequence == 0 && !await ClearStopsCoreAsync(exec.InstrumentId, exec.Strategy, instrument, cancellationToken).ConfigureAwait(false)) { // The stops on the quantity to sell must be gone first (SPEC 7.2); they come back if the sale stops. return null; } - if (exec.Side == OrderSide.Buy && exec.Step < 0 && _broker.Capabilities.OppositeSideBlocked + if (exec.Side == OrderSide.Buy && exec.Sequence == 0 && _broker.Capabilities.OppositeSideBlocked && !await ClearStopsCoreAsync(exec.InstrumentId, exec.Strategy, instrument, cancellationToken).ConfigureAwait(false)) { // Alpaca refuses a purchase while a sell stop rests on the symbol: cancel, buy, put back. @@ -726,7 +733,16 @@ public sealed partial class OrderManager : IDisposable private Task OrderByClientIdAsync(string clientId, CancellationToken cancellationToken) => _db.ReadAsync(s => s.FirstOrDefaultAsync(OrderSelect + " WHERE client_order_id = @c AND account_id = @a", ReadOrder, ("c", clientId), ("a", _account.AccountId)), cancellationToken); - private Task InsertOrderAsync(DbSession s, OrderRow row, CancellationToken cancellationToken) => s.ExecuteAsync( + /// A new order and its first event: the creation is part of the recorded history (SPEC 7.2). + private async Task InsertOrderAsync(DbSession s, OrderRow row, CancellationToken cancellationToken) + { + var inserted = await InsertOrderRowAsync(s, row, cancellationToken).ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO order_events (id, order_id, to_status, filled_quantity, note, occurred_at, created_at) VALUES (@id, @o, 'created', 0, 'created', @now, @now)", + cancellationToken, ("id", Ids.NewId(_clock)), ("o", row.Id), ("now", row.CreatedAt)).ConfigureAwait(false); + return inserted; + } + + private Task InsertOrderRowAsync(DbSession s, OrderRow row, CancellationToken cancellationToken) => s.ExecuteAsync( "INSERT INTO orders (id, account_id, instrument_id, strategy, client_order_id, side, order_type, quantity, limit_price, stop_price, status, created_at, updated_at, " + "purpose, time_in_force, post_only, reference_price, filled_quantity, step, execution_id) " + "VALUES (@id, @a, @i, @s, @c, @side, @k, @q, @l, @st, 'created', @now, @now, @p, @tif, @po, @r, 0, @step, @e)", cancellationToken, diff --git a/tests/Anubis.Tests/OrderManagerTests.cs b/tests/Anubis.Tests/OrderManagerTests.cs new file mode 100644 index 0000000..5045bc8 --- /dev/null +++ b/tests/Anubis.Tests/OrderManagerTests.cs @@ -0,0 +1,314 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// The order manager (issues #27, #28, #30, SPEC 7.2): chasing limit, pace, sales, server stops, faults. +[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 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 AlpacaAsync(Func>? 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 = Strategies.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 = Strategies.CryptoTrend) => + new(s.Instrument.Id, strategy, OrderSide.Sell, quantity, OrderPurpose.Exit, Ids.NewId(s.Rig.Clock)); + + private static Task> 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 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, Strategies.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, Strategies.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, Strategies.CryptoTrend, _none).ConfigureAwait(false))!.Quantity; + + // Nobody buys near the price: the sale keeps going with a fresh reference and double tolerance. + s.Rig.Quote("BTC-EUR", 50000m, 60000m); + var (execution, _) = await s.Manager.SubmitAsync(Sell(s, held), _none).ConfigureAwait(false); + 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(); + 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, Strategies.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, Strategies.CryptoTrend, _none).ConfigureAwait(false))!.Quantity; + + var buys = new List(); + 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, Strategies.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: Strategies.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: Strategies.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, Strategies.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, Strategies.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, Strategies.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, 10), "test", "split-msft") { Ratio = 4m } : null); + }).ConfigureAwait(false); + await a.Manager.SubmitAsync(Buy(a, 10m, aggressive: true, strategy: Strategies.EquityMomentum), _none).ConfigureAwait(false); + await a.Rig.TurnsAsync(a.Manager, 2, _minute).ConfigureAwait(false); + await a.Paper.ApplySplitAsync("MSFT", 4m, _none).ConfigureAwait(false); + a.Rig.Quote("MSFT", 100m, 100.05m); + await a.Rig.Ledger.SetStopAsync(a.Account.AccountId, a.Instrument.Id, Strategies.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, Strategies.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)); + } + + [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, Strategies.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, Strategies.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, Strategies.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."); + } +} diff --git a/tests/Anubis.Tests/PaperBrokerTests.cs b/tests/Anubis.Tests/PaperBrokerTests.cs new file mode 100644 index 0000000..31fbeb1 --- /dev/null +++ b/tests/Anubis.Tests/PaperBrokerTests.cs @@ -0,0 +1,158 @@ +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)); + } +} diff --git a/tests/Anubis.Tests/ReconcilerTests.cs b/tests/Anubis.Tests/ReconcilerTests.cs new file mode 100644 index 0000000..9ec157b --- /dev/null +++ b/tests/Anubis.Tests/ReconcilerTests.cs @@ -0,0 +1,219 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// Reconciliation (issue #30, SPEC 7.4): differences that explain themselves, prudent mode, the user's choice. +[TestClass] +public sealed class ReconcilerTests +{ + 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, FaultyBroker Broker, OrderManager Manager, Reconciler Reconciler) + : IAsyncDisposable + { + public ValueTask DisposeAsync() => Rig.DisposeAsync(); + } + + /// An OKX account holding 0.01 BTC with its stop at 57000; "demo" compares positions and orders with the account. + private static async Task HoldingAsync(string environment = TradingEnvironments.Demo) + { + var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var account = await rig.AccountAsync(Venues.Okx, environment).ConfigureAwait(false); + var instrument = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); + var paper = rig.Paper(PaperOptions.Okx(), account.AccountId); + await paper.DepositAsync(100_000m, "EUR", _none).ConfigureAwait(false); + await rig.Ledger.RecordCapitalAsync(account.AccountId, Strategies.CryptoTrend, 10_000m, "EUR", "test", _none).ConfigureAwait(false); + rig.Quote(instrument.Symbol, 60000m, 60010m); + var broker = new FaultyBroker(paper, environment); + var manager = rig.Manager(broker, account); + await manager.SubmitAsync(new TradeIntent(instrument.Id, Strategies.CryptoTrend, OrderSide.Buy, 0.01m, OrderPurpose.Entry, Ids.NewId(rig.Clock)) + { + StopLevel = 57000m, + StartAggressive = true, + }, _none).ConfigureAwait(false); + await TurnsAsync(rig, paper, manager, 2).ConfigureAwait(false); + return new Setup(rig, account, instrument, paper, broker, manager, new Reconciler(rig.Db, rig.Clock, rig.Ledger)); + } + + private static async Task TurnsAsync(TradingRig rig, PaperBroker paper, OrderManager manager, int turns) + { + for (var i = 0; i < turns; i++) + { + rig.Refresh(); + await paper.PumpAsync(_none).ConfigureAwait(false); + await manager.TickAsync(_none).ConfigureAwait(false); + rig.Clock.Advance(_minute); + } + } + + private static Task> CodesAsync(TradingRig rig, string code) => + rig.QueryAsync("SELECT code FROM journal WHERE code = @c", r => r.Text("code"), ("c", code)); + + private static TradeIntent Entry(Setup s) => new(s.Instrument.Id, Strategies.CryptoTrend, OrderSide.Buy, 0.001m, OrderPurpose.Entry, Ids.NewId(s.Rig.Clock)); + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task AnAccountThatAgreesIsCleanAndLeavesNoRow() + { + await using var s = await HoldingAsync().ConfigureAwait(false); + var report = await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false); + Assert.AreEqual((ReconcileOutcomes.Clean, AccountModes.Normal), (report.Outcome, report.Mode), string.Join("; ", report.Differences.Select(d => d.Message))); + Assert.IsEmpty(report.Differences); + Assert.IsEmpty(await s.Rig.QueryAsync("SELECT id FROM reconciliations", r => r.Id("id")).ConfigureAwait(false)); + var state = await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false); + Assert.AreEqual((ReconcileOutcomes.Clean, s.Rig.Clock.UtcNow), (state.LastOutcome, state.LastReconciledAt)); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task AStopThatFiredUnseenExplainsItselfWithTheLateFill() + { + await using var s = await HoldingAsync().ConfigureAwait(false); + + // The stop fires on the account while the bot looks elsewhere: the account holds nothing, the ledger 0.00998. + s.Rig.Quote("BTC-EUR", 56000m, 56010m); + await s.Paper.PumpAsync(_none).ConfigureAwait(false); + Assert.IsEmpty(await s.Paper.GetPositionsAsync(_none).ConfigureAwait(false)); + Assert.IsNotNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false)); + + var report = await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false); + Assert.AreEqual((ReconcileOutcomes.Healed, AccountModes.Normal), (report.Outcome, report.Mode), string.Join("; ", report.Differences.Select(d => d.Message))); + Assert.IsNull(await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false)); + Assert.AreEqual("stop", (await s.Rig.QueryAsync("SELECT exit_reason FROM trades", r => r.Text("exit_reason")).ConfigureAwait(false)).Single()); + Assert.HasCount(1, await CodesAsync(s.Rig, "reconcile_healed").ConfigureAwait(false)); + Assert.HasCount(1, await s.Rig.QueryAsync("SELECT id FROM reconciliations WHERE outcome = 'healed'", r => r.Id("id")).ConfigureAwait(false)); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task AnUnexplainedDifferenceMakesTheAccountPrudentUntilItClearsOrTheUserChooses() + { + await using var s = await HoldingAsync().ConfigureAwait(false); + + // Part of the coin is gone from the account and nothing explains it. + s.Broker.Missing["BTC-EUR"] = 0.004m; + var report = await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false); + Assert.AreEqual((ReconcileOutcomes.Different, AccountModes.Prudent), (report.Outcome, report.Mode)); + Assert.HasCount(1, report.Differences, string.Join("; ", report.Differences.Select(d => d.Message))); + Assert.AreEqual((DifferenceKinds.Position, 0.00998m, 0.00598m), (report.Differences.Single().Kind, report.Differences.Single().Ledger, report.Differences.Single().Broker)); + Assert.HasCount(1, await s.Rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'account_prudent'", r => r.Id("id")).ConfigureAwait(false)); + + // Prudent: no new purchases, sales still go. + Assert.AreEqual(OrderReasons.PrudentMode, (await s.Manager.SubmitAsync(Entry(s), _none).ConfigureAwait(false)).Refusal); + Assert.IsNull((await s.Manager.SubmitAsync(Entry(s) with { Side = OrderSide.Sell, Purpose = OrderPurpose.Exit }, _none).ConfigureAwait(false)).Refusal); + await s.Rig.Db.WriteAsync(x => x.ExecuteAsync("UPDATE executions SET status = 'canceled'", _none), _none).ConfigureAwait(false); + + // It clears within 15 minutes: back to normal by itself, notified once. + s.Rig.Clock.Advance(TimeSpan.FromMinutes(5)); + s.Broker.Missing.Clear(); + report = await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false); + Assert.AreEqual((ReconcileOutcomes.Clean, AccountModes.Normal), (report.Outcome, report.Mode)); + Assert.HasCount(1, await CodesAsync(s.Rig, "account_normal").ConfigureAwait(false)); + + // Again, and this time it stays: after 15 minutes only the user can close it, and it is not reported twice. + s.Broker.Missing["BTC-EUR"] = 0.004m; + await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false); + s.Rig.Clock.Advance(TimeSpan.FromMinutes(16)); + report = await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false); + Assert.AreEqual(AccountModes.Prudent, report.Mode); + var state = await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false); + Assert.IsTrue(state.WaitsForUser(s.Rig.Clock.UtcNow, s.Reconciler.Grace)); + Assert.HasCount(2, await s.Rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'account_prudent'", r => r.Id("id")).ConfigureAwait(false)); + + // Align: the ledger takes the account's number with an adjustment, and the account is normal again. + await s.Reconciler.ResolveAsync(s.Manager, ReconcileChoice.Align, "test", _none).ConfigureAwait(false); + Assert.AreEqual(0.00598m, (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false))!.Quantity); + state = await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false); + Assert.AreEqual((AccountModes.Normal, ReconcileOutcomes.UserAligned), (state.Mode, state.LastOutcome)); + Assert.HasCount(1, await CodesAsync(s.Rig, "account_resolved").ConfigureAwait(false)); + + // The stop follows the new quantity and the next round is clean. + await s.Manager.AlignStopsAsync(_none).ConfigureAwait(false); + report = await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false); + Assert.AreEqual(ReconcileOutcomes.Clean, report.Outcome, string.Join("; ", report.Differences.Select(d => d.Message))); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task AnUnknownOrderOfThisInstallationIsReportedAndCanBeLeftOut() + { + await using var s = await HoldingAsync().ConfigureAwait(false); + var stray = ClientOrderIds.Build(TradingRig.Installation, TradingEnvironments.Demo, Strategies.CryptoTrend, OrderPurpose.Entry, ClientOrderIds.Key(Guid.NewGuid()), 1); + await s.Paper.SubmitOrderAsync(new OrderRequest(stray, "BTC-EUR", OrderSide.Buy, OrderKind.Limit, 0.001m, TimeInForce.Gtc) { LimitPrice = 50000m }, _none).ConfigureAwait(false); + + // Someone else's order on the same account is none of the bot's business. + await s.Paper.SubmitOrderAsync(new OrderRequest("manual-1", "BTC-EUR", OrderSide.Buy, OrderKind.Limit, 0.001m, TimeInForce.Gtc) { LimitPrice = 50000m }, _none) + .ConfigureAwait(false); + + var report = await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false); + var difference = report.Differences.Single(); + Assert.AreEqual((DifferenceKinds.Order, stray), (difference.Kind, difference.Subject)); + Assert.AreEqual(AccountModes.Prudent, report.Mode); + + await s.Reconciler.ResolveAsync(s.Manager, ReconcileChoice.Exclude, "test", _none).ConfigureAwait(false); + report = await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false); + Assert.AreEqual((ReconcileOutcomes.Clean, AccountModes.Normal), (report.Outcome, report.Mode)); + var state = await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false); + CollectionAssert.AreEqual(new[] { difference.Fingerprint }, state.Excluded.ToArray()); + Assert.AreEqual(ReconcileOutcomes.UserExcluded, + (await s.Rig.QueryAsync("SELECT outcome FROM reconciliations ORDER BY occurred_at DESC, id DESC", r => r.Text("outcome")).ConfigureAwait(false))[0]); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task AMissingStopIsPutBackAndInTheSimulatorOnlyTheLedgerIsCompared() + { + await using var s = await HoldingAsync(TradingEnvironments.Simulation).ConfigureAwait(false); + var stop = (await s.Paper.GetOpenOrdersAsync(_none).ConfigureAwait(false)).Single(); + await s.Paper.CancelOrderAsync(stop.ClientOrderId, stop.Symbol, _none).ConfigureAwait(false); + + // Positions the simulator does not show are not compared there: only its own book exists. + s.Broker.Missing["BTC-EUR"] = 0.004m; + var report = await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false); + Assert.AreEqual(ReconcileOutcomes.Healed, report.Outcome, string.Join("; ", report.Differences.Select(d => d.Message))); + var now = (await s.Paper.GetOpenOrdersAsync(_none).ConfigureAwait(false)).Single(); + Assert.AreEqual((0.00998m, 57000m), (now.Quantity, now.StopPrice)); + Assert.AreNotEqual(stop.ClientOrderId, now.ClientOrderId); + + // A ledger that does not agree with itself is a difference everywhere. + await s.Rig.Db.WriteAsync(x => x.ExecuteAsync("UPDATE positions SET quantity = 0.5", _none), _none).ConfigureAwait(false); + report = await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false); + Assert.AreEqual(DifferenceKinds.Ledger, report.Differences.Single(d => d.Kind == DifferenceKinds.Ledger).Kind); + Assert.AreEqual(AccountModes.Prudent, report.Mode); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task AKeyThatMayWithdrawStopsPurchasesUntilItIsReplaced() + { + await using var s = await HoldingAsync().ConfigureAwait(false); + s.Broker.KeyCanWithdraw = true; + var permissions = await s.Reconciler.CheckKeyAsync(s.Manager, _none).ConfigureAwait(false); + Assert.IsTrue(permissions!.CanWithdraw); + var state = await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false); + Assert.AreEqual((AccountModes.Prudent, Reconciler.KeyReason, true), (state.Mode, state.ModeReason, state.KeyCanWithdraw)); + Assert.IsFalse(state.WaitsForUser(s.Rig.Clock.UtcNow.AddHours(1), s.Reconciler.Grace), "Not a choice to make: the key has to change."); + Assert.AreEqual(OrderReasons.PrudentMode, (await s.Manager.SubmitAsync(Entry(s), _none).ConfigureAwait(false)).Refusal); + + // A clean round does not bring it back, nor does the user's choice. + s.Rig.Clock.Advance(TimeSpan.FromMinutes(5)); + Assert.AreEqual(AccountModes.Prudent, (await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false)).Mode); + await Assert.ThrowsExactlyAsync(() => s.Reconciler.ResolveAsync(s.Manager, ReconcileChoice.Align, "test", _none)).ConfigureAwait(false); + Assert.HasCount(1, await s.Rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'key_can_withdraw'", r => r.Id("id")).ConfigureAwait(false)); + } + + [TestMethod] + [TestCategory(Category.Simulation)] + public async Task ABrokerThatDoesNotAnswerIsWrittenDownOnce() + { + await using var s = await HoldingAsync().ConfigureAwait(false); + s.Broker.Down = true; + Assert.AreEqual(ReconcileOutcomes.Unreachable, (await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false)).Outcome); + Assert.AreEqual(ReconcileOutcomes.Unreachable, (await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false)).Outcome); + Assert.HasCount(1, await CodesAsync(s.Rig, "reconcile_unreachable").ConfigureAwait(false)); + Assert.AreEqual(AccountModes.Normal, (await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false)).Mode, "Silence is not a difference."); + } +} diff --git a/tests/Anubis.Tests/TradingSupport.cs b/tests/Anubis.Tests/TradingSupport.cs index 255e124..f214f53 100644 --- a/tests/Anubis.Tests/TradingSupport.cs +++ b/tests/Anubis.Tests/TradingSupport.cs @@ -69,6 +69,15 @@ internal sealed class TradingRig : IAsyncDisposable public void Quote(string symbol, decimal bid, decimal ask, decimal? size = null) => _quotes[symbol] = new Quote(symbol, bid, ask, Clock.UtcNow) { BidSize = size, AskSize = size }; + /// The same prices, read again now: the feed is alive and the market has not moved. + public void Refresh() + { + foreach (var (symbol, quote) in _quotes) + { + _quotes[symbol] = quote with { At = Clock.UtcNow }; + } + } + public Task QuoteAsync(string symbol, CancellationToken cancellationToken) => Task.FromResult(QuotesDown ? null : _quotes.TryGetValue(symbol, out var quote) ? quote : null); @@ -89,6 +98,7 @@ internal sealed class TradingRig : IAsyncDisposable { var manager = new OrderManager(Db, Clock, Ledger, broker, account, Installation, FindAsync, QuoteAsync) { + StepTime = TimeSpan.FromSeconds(60), ConfirmPrice = QuoteAsync, MarketOpen = marketOpen ?? ((_, _) => Task.FromResult(true)), PendingSplit = pendingSplit, @@ -102,6 +112,7 @@ internal sealed class TradingRig : IAsyncDisposable { for (var i = 0; i < turns; i++) { + Refresh(); if (manager.Broker is PaperBroker paper) { await paper.PumpAsync(CancellationToken.None).ConfigureAwait(false); @@ -128,3 +139,92 @@ internal sealed class TradingRig : IAsyncDisposable await Test.DisposeAsync().ConfigureAwait(false); } } + +/// A broker in front of another one that can lose answers, refuse orders, repeat fills or go silent (fault tests, SPEC 7.4). +internal sealed class FaultyBroker(IBrokerAccount inner, string? environment = null) : IBrokerAccount +{ + /// Quantities the account no longer shows, by symbol: a difference the ledger cannot explain. + public Dictionary Missing { get; } = new(StringComparer.Ordinal); + + /// The key reports that it may withdraw. + public bool KeyCanWithdraw { get; set; } + + /// The next order reaches the broker but its answer is lost. + public bool LoseNextAnswer { get; set; } + + /// The next order is refused with this code. + public string? RejectNext { get; set; } + + /// Every fill is reported twice. + public bool DuplicateFills { get; set; } + + /// Every call fails as if the network were down. + public bool Down { get; set; } + + public List Sent { get; } = []; + + public string Venue => inner.Venue; + + public string Environment => environment ?? inner.Environment; + + public BrokerCapabilities Capabilities => inner.Capabilities; + + public Task ServerTimeAsync(CancellationToken cancellationToken) => Guard(() => inner.ServerTimeAsync(cancellationToken)); + + public Task GetAccountAsync(CancellationToken cancellationToken) => Guard(() => inner.GetAccountAsync(cancellationToken)); + + public async Task> GetPositionsAsync(CancellationToken cancellationToken) + { + var positions = await Guard(() => inner.GetPositionsAsync(cancellationToken)).ConfigureAwait(false); + return [.. positions.Select(p => p with { Quantity = p.Quantity - Missing.GetValueOrDefault(p.Symbol) })]; + } + + public Task> GetOpenOrdersAsync(CancellationToken cancellationToken) => Guard(() => inner.GetOpenOrdersAsync(cancellationToken)); + + public async Task SubmitOrderAsync(OrderRequest request, CancellationToken cancellationToken) + { + if (Down) + { + throw new BrokerException("rete giù", retryable: true); + } + + if (RejectNext is { } code) + { + RejectNext = null; + throw new OrderRejectedException("rifiutato", code); + } + + Sent.Add(request); + var answer = await inner.SubmitOrderAsync(request, cancellationToken).ConfigureAwait(false); + if (LoseNextAnswer) + { + LoseNextAnswer = false; + throw new BrokerException("risposta persa", retryable: true); + } + + return answer; + } + + public Task CancelOrderAsync(string clientOrderId, string symbol, CancellationToken cancellationToken) => Guard(async () => + { + await inner.CancelOrderAsync(clientOrderId, symbol, cancellationToken).ConfigureAwait(false); + return true; + }); + + public Task GetOrderAsync(string clientOrderId, string symbol, CancellationToken cancellationToken) => Guard(() => inner.GetOrderAsync(clientOrderId, symbol, cancellationToken)); + + public async Task> GetFillsAsync(DateTimeOffset since, CancellationToken cancellationToken) + { + var fills = await Guard(() => inner.GetFillsAsync(since, cancellationToken)).ConfigureAwait(false); + return DuplicateFills ? [.. fills, .. fills] : fills; + } + + public Task> GetCashActivitiesAsync(DateTimeOffset since, CancellationToken cancellationToken) => Guard(() => inner.GetCashActivitiesAsync(since, cancellationToken)); + + public Task GetKeyPermissionsAsync(CancellationToken cancellationToken) => + KeyCanWithdraw ? Task.FromResult(new KeyPermissions(true, true, true, "lettura, ordini, prelievi")) : Guard(() => inner.GetKeyPermissionsAsync(cancellationToken)); + + public IAsyncEnumerable StreamOrderUpdatesAsync(CancellationToken cancellationToken) => inner.StreamOrderUpdatesAsync(cancellationToken); + + private Task Guard(Func> call) => Down ? throw new BrokerException("rete giù", retryable: true) : call(); +} -- 2.54.1 From d2441df59229b395f04cc477ab1863550b5bec86 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 10 Nov 2026 20:47:01 +0100 Subject: [PATCH 3/7] Add the broker conformance battery and trading service tests (refs #26 #28 #29 #31) One abstract battery states the adapter contract (time and cash, an order's client id from send to cancel, well-formed orders, positions and fills with fees as costs, key permissions) and runs it on the internal simulator, on Alpaca's and OKX's documentation samples with stateful fakes, and on the demo accounts when the user's keys are in the environment (LiveDemo, inconclusive without them). The OKX sample key lists withdraw, and the adapter reports it. Service tests cover the accounts created without keys (no request leaves), stock strategies moving to the paper account only while their ledger is empty, the simulator funded from the ledgers once, and dividends and splits applied once each. The whole suite also passes on PostgreSQL. Co-Authored-By: Claude Opus 5.5 --- tests/Anubis.Tests/BrokerConformanceTests.cs | 368 +++++++++++++++++++ tests/Anubis.Tests/TradingServiceTests.cs | 141 +++++++ 2 files changed, 509 insertions(+) create mode 100644 tests/Anubis.Tests/BrokerConformanceTests.cs create mode 100644 tests/Anubis.Tests/TradingServiceTests.cs diff --git a/tests/Anubis.Tests/BrokerConformanceTests.cs b/tests/Anubis.Tests/BrokerConformanceTests.cs new file mode 100644 index 0000000..f3f7cc0 --- /dev/null +++ b/tests/Anubis.Tests/BrokerConformanceTests.cs @@ -0,0 +1,368 @@ +using System.Net; +using System.Text.Json; +using System.Text.Json.Nodes; +using Anubis.Brokers; +using Anubis.Core; +using Anubis.Data; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// What a conformance run needs: the adapter, an order far from the market and the account's currency. +internal sealed record ConformanceVenue(IBrokerAccount Broker, OrderRequest FarBuy, string Currency, IAsyncDisposable? Owner = null); + +/// +/// The conformance battery (issue #31, SPEC 5.3): every adapter keeps the same contract, so the order manager and +/// reconciliation work the same on the internal simulator, on the brokers' documentation samples and, when the +/// user has given demo keys, on the real demo accounts. Each venue is a subclass that only says how to open it. +/// +public abstract class BrokerConformance +{ + protected static readonly CancellationToken None = CancellationToken.None; + + /// Opens the venue; is the id the battery's order will carry. + internal abstract Task OpenAsync(string clientOrderId); + + /// The documentation's sample key may withdraw: the adapter must say so, never hide it. + protected virtual bool KeyMayWithdraw => false; + + protected abstract string Environment { get; } + + private string ClientId() => + ClientOrderIds.Build(TradingRig.Installation, Environment, Strategies.CryptoTrend, OrderPurpose.Entry, ClientOrderIds.Key(new Guid("0193a7c0-0000-7000-8000-000000000031")), 1); + + [TestMethod] + public async Task TheVenueAnswersWithItsTimeAndItsCash() + { + var venue = await OpenAsync(ClientId()).ConfigureAwait(false); + try + { + Assert.IsGreaterThan(2019, (await venue.Broker.ServerTimeAsync(None).ConfigureAwait(false)).Year); + var account = await venue.Broker.GetAccountAsync(None).ConfigureAwait(false); + Assert.AreEqual(venue.Currency, account.Currency); + Assert.IsTrue(account.Cash.Values.All(c => c >= 0m), "Cash is never negative on an account without leverage."); + Assert.IsTrue(account.BuyingPower is null or >= 0m); + } + finally + { + await DisposeAsync(venue).ConfigureAwait(false); + } + } + + [TestMethod] + public async Task AnOrderKeepsItsClientIdFromSendToCancel() + { + var id = ClientId(); + var venue = await OpenAsync(id).ConfigureAwait(false); + try + { + var request = venue.FarBuy with { ClientOrderId = id }; + var sent = await venue.Broker.SubmitOrderAsync(request, None).ConfigureAwait(false); + Assert.AreEqual((id, request.Symbol, OrderSide.Buy, OrderKind.Limit), (sent.ClientOrderId, sent.Symbol, sent.Side, sent.Kind)); + Assert.IsTrue(sent.IsOpen, sent.Status.ToString()); + Assert.IsFalse(string.IsNullOrEmpty(sent.BrokerOrderId)); + + var read = await venue.Broker.GetOrderAsync(id, request.Symbol, None).ConfigureAwait(false); + Assert.AreEqual((id, request.Quantity, request.LimitPrice), (read!.ClientOrderId, read.Quantity, read.LimitPrice)); + Assert.IsTrue(read.IsOpen); + Assert.Contains(id, (await venue.Broker.GetOpenOrdersAsync(None).ConfigureAwait(false)).Select(o => o.ClientOrderId).ToList()); + + await venue.Broker.CancelOrderAsync(id, request.Symbol, None).ConfigureAwait(false); + var canceled = await venue.Broker.GetOrderAsync(id, request.Symbol, None).ConfigureAwait(false); + Assert.AreEqual(OrderStatus.Canceled, canceled!.Status); + Assert.DoesNotContain(id, (await venue.Broker.GetOpenOrdersAsync(None).ConfigureAwait(false)).Select(o => o.ClientOrderId).ToList()); + + // Canceling again, or an order the venue never saw, is not an error: the caller reads the order next. + await venue.Broker.CancelOrderAsync(id, request.Symbol, None).ConfigureAwait(false); + var unknown = id[..^1] + (id[^1] == '9' ? '8' : '9'); + Assert.IsNull(await venue.Broker.GetOrderAsync(unknown, request.Symbol, None).ConfigureAwait(false)); + } + finally + { + await DisposeAsync(venue).ConfigureAwait(false); + } + } + + [TestMethod] + public async Task OrdersPositionsAndFillsAreWellFormed() + { + var venue = await OpenAsync(ClientId()).ConfigureAwait(false); + try + { + foreach (var order in await venue.Broker.GetOpenOrdersAsync(None).ConfigureAwait(false)) + { + Assert.IsFalse(string.IsNullOrEmpty(order.Symbol)); + Assert.IsTrue(order.Quantity > 0m && order.Remaining >= 0m && order.Remaining <= order.Quantity, order.ClientOrderId); + Assert.IsTrue(order.IsOpen); + } + + foreach (var position in await venue.Broker.GetPositionsAsync(None).ConfigureAwait(false)) + { + Assert.IsFalse(string.IsNullOrEmpty(position.Symbol)); + Assert.IsGreaterThan(0m, position.Quantity, position.Symbol); + } + + foreach (var fill in await venue.Broker.GetFillsAsync(DateTimeOffset.UnixEpoch, None).ConfigureAwait(false)) + { + Assert.IsFalse(string.IsNullOrEmpty(fill.ExecutionId)); + Assert.IsTrue(fill.Quantity > 0m && fill.Price > 0m, fill.ExecutionId); + Assert.IsGreaterThanOrEqualTo(0m, fill.Fee, "A fee is a cost: the adapter turns the venue's sign around."); + Assert.IsFalse(string.IsNullOrEmpty(fill.FeeCurrency)); + } + + foreach (var activity in await venue.Broker.GetCashActivitiesAsync(DateTimeOffset.UnixEpoch, None).ConfigureAwait(false)) + { + Assert.IsFalse(string.IsNullOrEmpty(activity.Id)); + } + } + finally + { + await DisposeAsync(venue).ConfigureAwait(false); + } + } + + [TestMethod] + public async Task TheKeyTellsWhatItMayDo() + { + var venue = await OpenAsync(ClientId()).ConfigureAwait(false); + try + { + var key = await venue.Broker.GetKeyPermissionsAsync(None).ConfigureAwait(false); + Assert.AreEqual((true, true, KeyMayWithdraw), (key.CanRead, key.CanTrade, key.CanWithdraw)); + Assert.IsFalse(string.IsNullOrWhiteSpace(key.Description)); + } + finally + { + await DisposeAsync(venue).ConfigureAwait(false); + } + } + + private static async Task DisposeAsync(ConformanceVenue venue) + { + if (venue.Owner is not null) + { + await venue.Owner.DisposeAsync().ConfigureAwait(false); + } + } +} + +/// The internal simulator. +[TestClass] +[TestCategory(Category.Simulation)] +public sealed class PaperBrokerConformance : BrokerConformance +{ + protected override string Environment => TradingEnvironments.Simulation; + + internal override async Task OpenAsync(string clientOrderId) + { + 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); + rig.Quote("BTC-EUR", 60000m, 60010m); + var paper = rig.Paper(PaperOptions.Okx(), account.AccountId); + await paper.DepositAsync(10_000m, "EUR", None).ConfigureAwait(false); + + // Something held and something filled, so the shapes are checked on real content. + await paper.SubmitOrderAsync(new OrderRequest("seed-buy", "BTC-EUR", OrderSide.Buy, OrderKind.Market, 0.01m, TimeInForce.Gtc), None).ConfigureAwait(false); + await paper.PumpAsync(None).ConfigureAwait(false); + return new ConformanceVenue(paper, new OrderRequest(clientOrderId, "BTC-EUR", OrderSide.Buy, OrderKind.Limit, 0.001m, TimeInForce.Gtc) { LimitPrice = 30000m }, "EUR", rig); + } +} + +/// +/// Alpaca's trading API on the samples of its documentation (Fixtures/alpaca-trading), with the order's state +/// following what the adapter does: open after the send, canceled after the DELETE. +/// +[TestClass] +[TestCategory(Category.Unit)] +public sealed class AlpacaDocConformance : BrokerConformance +{ + protected override string Environment => TradingEnvironments.Demo; + + internal override Task OpenAsync(string clientOrderId) + { + var order = JsonNode.Parse(Fixture.Text("alpaca-trading/order-limit.json"))!.AsObject(); + order["client_order_id"] = clientOrderId; + var brokerId = order["id"]!.GetValue(); + var placed = false; + var canceled = false; + string Order() => Status(order, !placed ? "unknown" : canceled ? "canceled" : "accepted"); + + // The fill's order, as the orders list of the same period shows it. + var filledOrder = JsonNode.Parse(Fixture.Text("alpaca-trading/order-limit.json"))!.AsObject(); + filledOrder["id"] = JsonNode.Parse(Fixture.Text("alpaca-trading/activity-fill.json"))!["order_id"]!.GetValue(); + filledOrder["client_order_id"] = "manual-order"; + + var http = new FakeHttp() + .On("/v2/clock", Fixture.Text("alpaca/clock-v2.json")) + .On(u => u.AbsolutePath == "/v2/account", _ => FakeHttp.Respond(Fixture.Text("alpaca-trading/account.json"))) + .On("/v2/positions", "[" + Fixture.Text("alpaca-trading/position.json") + "]") + .On(u => u.AbsolutePath.StartsWith("/v2/orders:by_client_order_id", StringComparison.Ordinal), r => + placed && r.RequestUri!.Query.Contains(Uri.EscapeDataString(clientOrderId), StringComparison.Ordinal) + ? FakeHttp.Respond(Order()) + : FakeHttp.Respond("{\"code\":40410000,\"message\":\"order not found\"}", HttpStatusCode.NotFound)) + .On(u => u.AbsolutePath == "/v2/orders/" + brokerId, r => + { + canceled = r.Method == HttpMethod.Delete || canceled; + return r.Method == HttpMethod.Delete ? new HttpResponseMessage(HttpStatusCode.NoContent) : FakeHttp.Respond(Order()); + }) + .On(u => u.AbsolutePath == "/v2/orders", r => + { + if (r.Method == HttpMethod.Post) + { + placed = true; + return FakeHttp.Respond(Order()); + } + + var query = r.RequestUri!.Query; + return FakeHttp.Respond(query.Contains("status=open", StringComparison.Ordinal) + ? (placed && !canceled ? "[" + Order() + "]" : "[]") + : "[" + filledOrder.ToJsonString() + "]"); + }) + .On(u => u.AbsolutePath == "/v2/account/activities", r => FakeHttp.Respond(r.RequestUri!.Query.Contains("FILL", StringComparison.Ordinal) + ? "[" + Fixture.Text("alpaca-trading/activity-fill.json") + "]" + : "[" + Fixture.Text("alpaca-trading/activity-div.json") + "]")); + var adapter = new AlpacaTrading(http.Client(), new ManualClock(TradingRig.Start), new AlpacaCredentials("doc-key-id", "doc-secret"), + new AlpacaTradingOptions { Environment = TradingEnvironments.Demo }, TradingConsent.None); + return Task.FromResult(new ConformanceVenue(adapter, + new OrderRequest(clientOrderId, "AAPL", OrderSide.Buy, OrderKind.Limit, 2m, TimeInForce.Gtc) { LimitPrice = 150m }, "USD")); + } + + private static string Status(JsonObject order, string status) + { + var copy = order.DeepClone().AsObject(); + copy["status"] = status; + return copy.ToJsonString(); + } +} + +/// OKX Europe on the samples of its documentation (Fixtures/okx-trading), in USDT as the samples are. +[TestClass] +[TestCategory(Category.Unit)] +public sealed class OkxDocConformance : BrokerConformance +{ + /// The documentation's account configuration lists withdraw among the key's permissions. + protected override bool KeyMayWithdraw => true; + + protected override string Environment => TradingEnvironments.Demo; + + internal override Task OpenAsync(string clientOrderId) + { + var pending = JsonNode.Parse(Fixture.Text("okx-trading/orders-pending.json"))!["data"]![0]!.AsObject(); + pending["clOrdId"] = clientOrderId; + var placed = false; + var canceled = false; + string Order() => Envelope(Status(pending, canceled ? "canceled" : "live")); + + var http = new FakeHttp() + .On("/api/v5/public/time", "{\"code\":\"0\",\"msg\":\"\",\"data\":[{\"ts\":\"1597026383085\"}]}") + .On("/api/v5/account/balance", Fixture.Text("okx-trading/balance.json")) + .On("/api/v5/account/config", Fixture.Text("okx-trading/account-config.json")) + .On(u => u.AbsolutePath == "/api/v5/trade/orders-pending", _ => FakeHttp.Respond(placed && !canceled ? Envelope(pending.ToJsonString()) : "{\"code\":\"0\",\"msg\":\"\",\"data\":[]}")) + .On("/api/v5/trade/orders-algo-pending", Fixture.Text("okx-trading/algos-pending.json")) + .On(u => u.AbsolutePath == "/api/v5/trade/order", r => + { + if (r.Method == HttpMethod.Post) + { + placed = true; + return FakeHttp.Respond(Fixture.Text("okx-trading/order-placed.json").Replace("oktswap6", clientOrderId, StringComparison.Ordinal)); + } + + var query = r.RequestUri!.Query; + if (query.Contains("ordId=", StringComparison.Ordinal) && !query.Contains("clOrdId=", StringComparison.Ordinal)) + { + return FakeHttp.Respond(Fixture.Text("okx-trading/order-filled.json")); + } + + return placed && query.Contains("clOrdId=" + clientOrderId, StringComparison.Ordinal) + ? FakeHttp.Respond(Order()) + : FakeHttp.Respond("{\"code\":\"51603\",\"msg\":\"Order does not exist\",\"data\":[]}"); + }) + .On(u => u.AbsolutePath == "/api/v5/trade/cancel-order", _ => + { + var already = canceled; + canceled = true; + return FakeHttp.Respond(already + ? "{\"code\":\"1\",\"msg\":\"\",\"data\":[{\"clOrdId\":\"" + clientOrderId + "\",\"ordId\":\"\",\"sCode\":\"51400\",\"sMsg\":\"Order cancellation failed as the order has been filled, canceled or does not exist\"}]}" + : Fixture.Text("okx-trading/order-canceled.json").Replace("oktswap6", clientOrderId, StringComparison.Ordinal)); + }) + .On("/api/v5/trade/fills", Fixture.Text("okx-trading/fills.json")); + var adapter = new OkxTrading(http.Client(), new ManualClock(TradingRig.Start), new OkxCredentials("doc-key", "doc-secret", "doc-pass"), + new OkxTradingOptions { Environment = TradingEnvironments.Demo, QuoteCurrency = "USDT" }, TradingConsent.None); + var px = decimal.Parse(pending["px"]!.GetValue(), System.Globalization.CultureInfo.InvariantCulture); + var sz = decimal.Parse(pending["sz"]!.GetValue(), System.Globalization.CultureInfo.InvariantCulture); + return Task.FromResult(new ConformanceVenue(adapter, + new OrderRequest(clientOrderId, pending["instId"]!.GetValue(), OrderSide.Buy, OrderKind.Limit, sz, TimeInForce.Gtc) { LimitPrice = px }, "USDT")); + } + + private static string Status(JsonObject order, string state) + { + var copy = order.DeepClone().AsObject(); + copy["state"] = state; + copy["ordType"] = "limit"; + return copy.ToJsonString(); + } + + private static string Envelope(string item) => "{\"code\":\"0\",\"msg\":\"\",\"data\":[" + item + "]}"; +} + +/// +/// The same battery on the real demo accounts, with the keys the user puts in the environment. Without them the +/// tests are inconclusive: the criterion is waiting for the user (issue #31). Never a live account (SPEC 2.2). +/// +[TestClass] +[TestCategory(Category.LiveDemo)] +public sealed class AlpacaPaperConformance : BrokerConformance +{ + protected override string Environment => TradingEnvironments.Demo; + + internal override Task OpenAsync(string clientOrderId) + { + var key = System.Environment.GetEnvironmentVariable("ALPACA_API_KEY_DEMO"); + var secret = System.Environment.GetEnvironmentVariable("ALPACA_API_SECRET_DEMO"); + if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(secret)) + { + Assert.Inconclusive("In attesa dell'utente: servono le chiavi del conto paper di Alpaca."); + } + + var http = new HttpClient(); + var adapter = new AlpacaTrading(http, SystemClock.Instance, new AlpacaCredentials(key, secret), new AlpacaTradingOptions { Environment = TradingEnvironments.Demo }, + TradingConsent.None); + return Task.FromResult(new ConformanceVenue(adapter, + new OrderRequest(clientOrderId, "AAPL", OrderSide.Buy, OrderKind.Limit, 1m, TimeInForce.Day) { LimitPrice = 1m }, "USD", new HttpOwner(http))); + } +} + +/// The battery on the OKX Europe demo account, with the user's demo keys. +[TestClass] +[TestCategory(Category.LiveDemo)] +public sealed class OkxDemoConformance : BrokerConformance +{ + protected override string Environment => TradingEnvironments.Demo; + + internal override Task OpenAsync(string clientOrderId) + { + var key = System.Environment.GetEnvironmentVariable("OKX_API_KEY_DEMO"); + var secret = System.Environment.GetEnvironmentVariable("OKX_API_SECRET_DEMO"); + var passphrase = System.Environment.GetEnvironmentVariable("OKX_API_PASSPHRASE_DEMO"); + if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(secret) || string.IsNullOrEmpty(passphrase)) + { + Assert.Inconclusive("In attesa dell'utente: servono le chiavi del conto demo di OKX."); + } + + var http = new HttpClient(); + var adapter = new OkxTrading(http, SystemClock.Instance, new OkxCredentials(key, secret, passphrase), new OkxTradingOptions { Environment = TradingEnvironments.Demo }, + TradingConsent.None); + return Task.FromResult(new ConformanceVenue(adapter, + new OrderRequest(clientOrderId, "BTC-EUR", OrderSide.Buy, OrderKind.Limit, 0.0001m, TimeInForce.Gtc) { LimitPrice = 10000m }, "EUR", new HttpOwner(http))); + } +} + +internal sealed class HttpOwner(HttpClient http) : IAsyncDisposable +{ + public ValueTask DisposeAsync() + { + http.Dispose(); + return ValueTask.CompletedTask; + } +} diff --git a/tests/Anubis.Tests/TradingServiceTests.cs b/tests/Anubis.Tests/TradingServiceTests.cs new file mode 100644 index 0000000..00830df --- /dev/null +++ b/tests/Anubis.Tests/TradingServiceTests.cs @@ -0,0 +1,141 @@ +using Anubis.Core; +using Anubis.Data; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// The trading service (issues #26, #28, #29): accounts, the simulator's money, corporate actions. +[TestClass] +public sealed class TradingServiceTests +{ + private static readonly CancellationToken _none = CancellationToken.None; + + private static TradingService Service(TradingRig rig, FakeHttp http, IReadOnlyDictionary? keys = null) => + new(rig.Db, rig.Clock, new EventBus(), new SecretStore(rig.Db, rig.Clock, new byte[32], keys), null, new FxStore(rig.Db, rig.Clock), TradingConsent.None, + new Guid("0193a7c0-0000-7000-8000-0000000000aa"), http); + + private static Task> StrategiesAsync(TradingRig rig) => + rig.QueryAsync("SELECT s.strategy, a.name, s.stage FROM strategy_state s JOIN accounts a ON a.id = s.account_id ORDER BY s.strategy", + r => (r.Text("strategy"), r.Text("name"), r.Text("stage"))); + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task WithoutKeysBothSimulatorsRunAndNothingLeavesTheHouse() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var http = new FakeHttp(); + using var service = Service(rig, http); + await service.StartAsync(_none).ConfigureAwait(false); + + var accounts = await rig.QueryAsync("SELECT name, environment FROM accounts ORDER BY name", r => (r.Text("name"), r.Text("environment"))).ConfigureAwait(false); + CollectionAssert.AreEqual(new[] { ("Alpaca simulatore", "simulation"), ("OKX simulatore", "simulation") }, accounts.ToArray()); + Assert.HasCount(2, service.Managers); + Assert.IsTrue(service.Managers.All(m => m.Broker is PaperBroker)); + Assert.IsEmpty(http.Requests, "No keys, no requests."); + + // Every strategy starts in observation, crypto on OKX and stocks on Alpaca. + CollectionAssert.AreEqual(new[] + { + (Strategies.CryptoTrend, "OKX simulatore", Strategies.Observation), + (Strategies.EquityMeanrev, "Alpaca simulatore", Strategies.Observation), + (Strategies.EquityMomentum, "Alpaca simulatore", Strategies.Observation), + }, (await StrategiesAsync(rig).ConfigureAwait(false)).ToArray()); + + // A second start finds what is there. + using var again = Service(rig, http); + await again.StartAsync(_none).ConfigureAwait(false); + Assert.HasCount(2, await rig.QueryAsync("SELECT id FROM accounts", r => r.Id("id")).ConfigureAwait(false)); + Assert.HasCount(3, await StrategiesAsync(rig).ConfigureAwait(false)); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task StockStrategiesMoveToThePaperAccountOnlyWhileTheirLedgerIsEmpty() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var accounts = await AccountSetup.EnsureAsync(rig.Db, rig.Clock, alpacaDemo: false, okxDemo: false, _none).ConfigureAwait(false); + var simulator = accounts.Single(a => a.Broker == Venues.Alpaca); + await rig.Ledger.RecordCapitalAsync(simulator.AccountId, Strategies.EquityMeanrev, 500m, "USD", "test", _none).ConfigureAwait(false); + + accounts = await AccountSetup.EnsureAsync(rig.Db, rig.Clock, alpacaDemo: true, okxDemo: false, _none).ConfigureAwait(false); + Assert.HasCount(3, accounts); + Assert.IsFalse(accounts.Any(a => a.Environment == TradingEnvironments.Live), "Never a real account in this phase (SPEC 2.2)."); + CollectionAssert.AreEqual(new[] + { + (Strategies.CryptoTrend, "OKX simulatore", Strategies.Observation), + (Strategies.EquityMeanrev, "Alpaca simulatore", Strategies.Observation), + (Strategies.EquityMomentum, "Alpaca paper", Strategies.Observation), + }, (await StrategiesAsync(rig).ConfigureAwait(false)).ToArray(), "A strategy with a history stays where it is."); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheSimulatorHoldsTheMoneyItsLedgersGive() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + await new FxStore(rig.Db, rig.Clock).UpsertAsync([new FxRate("EUR", "USD", new DateOnly(2026, 11, 9), 1.10m, "ecb")], _none).ConfigureAwait(false); + using var service = Service(rig, new FakeHttp()); + await service.StartAsync(_none).ConfigureAwait(false); + + await service.SetCapitalAsync(Venues.Okx, 1000m, "test", _none).ConfigureAwait(false); + var alpaca = await service.SetCapitalAsync(Venues.Alpaca, 2000m, "test", _none).ConfigureAwait(false); + Assert.AreEqual((2200m, 1.10m), (alpaca.Amount, alpaca.FxRate)); + await service.FundSimulatorsAsync(_none).ConfigureAwait(false); + + async Task BookAsync(string broker, string currency) + { + var paper = (PaperBroker)service.Managers.Single(m => m.Account.Broker == broker).Broker; + return (await paper.GetAccountAsync(_none).ConfigureAwait(false)).Cash.GetValueOrDefault(currency); + } + + Assert.AreEqual(1000m, await BookAsync(Venues.Okx, "EUR").ConfigureAwait(false)); + Assert.AreEqual(2200m, await BookAsync(Venues.Alpaca, "USD").ConfigureAwait(false), "Funded once, not again at every call."); + var shares = await rig.QueryAsync("SELECT strategy, capital FROM strategy_state ORDER BY strategy", r => (r.Text("strategy"), r.Money("capital"))).ConfigureAwait(false); + CollectionAssert.AreEqual(new[] { (Strategies.CryptoTrend, 1000m), (Strategies.EquityMeanrev, 550m), (Strategies.EquityMomentum, 1650m) }, shares.ToArray()); + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task DividendsAndSplitsReachTheLedgersOnce() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var http = new FakeHttp(); + using var service = Service(rig, http); + var msft = await rig.InstrumentAsync(TradingRig.Stock("MSFT")).ConfigureAwait(false); + await service.StartAsync(_none).ConfigureAwait(false); + var account = service.Managers.Single(m => m.Account.Broker == Venues.Alpaca).Account; + await service.Ledger.RecordCapitalAsync(account.AccountId, Strategies.EquityMomentum, 5000m, "USD", "test", _none).ConfigureAwait(false); + await service.Ledger.RecordFillAsync(rig.Fill(account, msft, Strategies.EquityMomentum, OrderSide.Buy, 10m, 400m, feeCurrency: "USD"), _none).ConfigureAwait(false); + + // Bought on Tuesday; Wednesday is the ex-date of 0,75 USD a share; Thursday a 2-for-1 split. + await rig.Db.WriteAsync(async s => + { + foreach (var (kind, day, ratio, cash, key) in new[] { ("cash_dividend", "2026-11-11", (decimal?)null, (decimal?)0.75m, "div-msft"), ("split", "2026-11-12", 2m, null, "split-msft") }) + { + await s.ExecuteAsync("INSERT INTO corporate_actions (id, symbol, kind, ex_date, ratio, cash_amount, currency, source, source_key, created_at) " + + "VALUES (@id, 'MSFT', @k, @d, @r, @c, 'USD', 'test', @key, @now)", _none, + ("id", Ids.NewId(rig.Clock)), ("k", kind), ("d", day), ("r", ratio), ("c", cash), ("key", key), ("now", rig.Clock.UtcNow)).ConfigureAwait(false); + } + }, _none).ConfigureAwait(false); + + Task> DividendsAsync() => rig.QueryAsync("SELECT amount FROM cash_ledger WHERE kind = 'dividend'", r => r.Money("amount")); + + await service.CorporateActionsAsync(_none).ConfigureAwait(false); + Assert.IsEmpty(await DividendsAsync().ConfigureAwait(false), "Nothing before the ex-date."); + + rig.Clock.Advance(TimeSpan.FromDays(1)); + await service.CorporateActionsAsync(_none).ConfigureAwait(false); + await service.CorporateActionsAsync(_none).ConfigureAwait(false); + CollectionAssert.AreEqual(new[] { 7.5m }, (await DividendsAsync().ConfigureAwait(false)).ToArray()); + Assert.AreEqual(10m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!.Quantity); + + rig.Clock.Advance(TimeSpan.FromDays(1)); + await service.CorporateActionsAsync(_none).ConfigureAwait(false); + await service.CorporateActionsAsync(_none).ConfigureAwait(false); + var position = (await service.Ledger.PositionAsync(account.AccountId, msft.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!; + Assert.AreEqual((20m, 200m), (position.Quantity, position.AveragePrice)); + Assert.HasCount(1, await DividendsAsync().ConfigureAwait(false)); + Assert.HasCount(1, await rig.QueryAsync("SELECT code FROM journal WHERE code = 'split_applied'", r => r.Text("code")).ConfigureAwait(false)); + Assert.IsEmpty(http.Requests); + } +} -- 2.54.1 From 4c4f848d802c68545931de22729693c577831b46 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 10 Nov 2026 21:16:42 +0100 Subject: [PATCH 4/7] Add the Conti screen, account keys and entrusted capital (refs #32 #29 #31) The Conti e posizioni screen follows mockup 02: totals split by strategy, one card per account with key permissions and the last reconciliation, positions with a per-account filter and CSV export, pending stops (Alpaca grouped into permanent and day stops), residues, and exposure by currency. It shows one world only, real accounts when there are any, so simulated and real money never add up. Position values are rounded to the cent per row, as the table shows them, so the figures add up on screen. Settings gain "Conti e chiavi": practice keys are asked to the broker before they are saved and refused when they may withdraw or cannot trade; they are never shown again and the engine restarts to use them. The capital entrusted to each broker is set there in euro. Until any capital is set, the overview points to that section as the first step. The overview now reads one world, nets capital flows out of its results and uses the time-weighted index; open orders exclude protective stops. The demo seed gains cash rows, closed trades, stops, the ECB rate and the reconciliation state, so the ledger itself computes the mockup's figures. Screenshots now capture the whole page and include Conti. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- src/Anubis.Server/AccountsView.cs | 278 ++++++++++++ src/Anubis.Server/AnubisHost.cs | 9 + src/Anubis.Server/Assets/app.css | 71 +++ src/Anubis.Server/Components/Icon.razor | 3 + .../Components/Pages/Conti.razor | 410 +++++++++++++++++- .../Components/Pages/Impostazioni.razor | 125 +++++- .../Components/Pages/Panoramica.razor | 4 + src/Anubis.Server/Endpoints.cs | 10 + src/Anubis.Server/Forms.cs | 163 +++++++ src/Anubis.Server/Overview.cs | 50 ++- src/Anubis/Demo/DemoMode.cs | 167 ++++++- src/Anubis/Trading/Capital.cs | 9 + src/Anubis/Trading/TradingService.cs | 31 ++ tests/Anubis.Tests/AccountsScreenTests.cs | 152 +++++++ tests/Anubis.Tests/ServerHarness.cs | 3 +- tools/Anubis.Tasks/Program.cs | 2 +- tools/Anubis.Tasks/Shots.cs | 16 + 18 files changed, 1472 insertions(+), 33 deletions(-) create mode 100644 src/Anubis.Server/AccountsView.cs create mode 100644 tests/Anubis.Tests/AccountsScreenTests.cs diff --git a/CLAUDE.md b/CLAUDE.md index 4ab29db..96210ef 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -19,7 +19,7 @@ Dalla radice del repository: `./tasks.ps1 ` (Windows) o `sh ./tasks.sh - `ci`: come la CI. Esegue `check`, poi i test su PostgreSQL (avvia `docker compose up -d --wait postgres`, porta 55432) e infine l'immagine. Richiede Docker. - `hooks`: attiva `.githooks/pre-commit`, che esegue `check` prima di ogni commit. Si fa una volta per copia del repository. - `seed-demo`: la modalità dimostrativa con i dati dell'appendice F, in una cartella e un database a parte, solo dal computer stesso. -- `screenshots`: fotografa Panoramica, Diario e Impostazioni a 1440 px (chiaro e scuro) e a 390 px in `artifacts/screenshots/`. Usa Edge o Chrome già installati. +- `screenshots`: fotografa Panoramica, Conti, Diario e Impostazioni a 1440 px (chiaro e scuro) e a 390 px in `artifacts/screenshots/`. Usa Edge o Chrome già installati. - `desktop-win` (Fase 10): non ancora disponibile. - `docker compose up --build`: l'applicazione su http://localhost:8787 con PostgreSQL, `/health` risponde `ok`. Primo accesso con `ANUBIS_ADMIN_PASSWORD` del compose. diff --git a/src/Anubis.Server/AccountsView.cs b/src/Anubis.Server/AccountsView.cs new file mode 100644 index 0000000..4e8bcc8 --- /dev/null +++ b/src/Anubis.Server/AccountsView.cs @@ -0,0 +1,278 @@ +using System.Globalization; +using System.Text; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.Trading; + +namespace Anubis.Server; + +/// One account of the Conti screen, in its own currency and in euro. +internal sealed record AccountCard(Guid Id, string Name, string Broker, string Environment, string Currency, decimal Cash, decimal Invested, decimal InvestedEur, int Holdings, + decimal Realized, decimal Unrealized, decimal Fees, decimal Flows, AccountState State, decimal Rate) +{ + /// Cash plus the positions, each valued to the cent as the table shows it, so the figures add up on screen. + public decimal Equity => Cash + Invested; + + public string Kind => Broker == Venues.Alpaca ? "Azioni USA" : "Crypto"; + + public string Short => Broker == Venues.Alpaca ? "Alpaca" : "OKX"; + + public decimal Result => Equity - Flows; + + public decimal Percent => Flows > 0m ? Result / Flows * 100m : 0m; + + /// An amount of this account in euro, at the latest rate. + public decimal Eur(decimal amount) => Currency == "EUR" || Rate <= 0m ? amount : amount / Rate; +} + +internal sealed record PositionRow(Guid AccountId, string Broker, string Symbol, string Name, string Strategy, decimal Quantity, decimal Average, decimal Last, decimal? Stop, + string Currency, DateTimeOffset OpenedAt, decimal ValueEur, decimal ResultEur) +{ + public decimal Percent => Average == 0m ? 0m : (Last / Average - 1m) * 100m; +} + +/// A line of "Ordini in attesa": one order, or the stops of Alpaca grouped by validity. +internal sealed record PendingRow(string Action, string Subject, string Where, string Level, string Status, bool Waiting); + +internal sealed record ResidueRow(string Broker, string Symbol, decimal Quantity, decimal Value, string Currency, DateTimeOffset At); + +internal sealed record StrategySlice(string Label, string Color, decimal Eur); + +/// +/// The Conti e posizioni screen (SPEC 13.6, mockup 02): totals, accounts with key and reconciliation, open positions, +/// pending orders, residues and where the money is by currency. One world only: real accounts when there are any, +/// otherwise the simulated ones, so finto and vero never add up (SPEC 7.1). +/// +internal sealed record AccountsView( + IReadOnlyList Accounts, + IReadOnlyList Positions, + IReadOnlyList Pending, + int PendingOthers, + bool AlpacaStops, + IReadOnlyList Residues, + IReadOnlyList Slices, + decimal? UsdRate, + DateOnly? RateDay, + decimal? FxEffect, + bool MarketOpen, + DateTimeOffset MarketNext) +{ + public bool HasAccounts => Accounts.Count > 0; + + public decimal TotalEur => Accounts.Sum(a => a.Eur(a.Equity)); + + public decimal CashEur => Accounts.Sum(a => a.Eur(a.Cash)); + + public decimal InvestedEur => Accounts.Sum(a => a.InvestedEur); + + public decimal ResultEur => Accounts.Sum(a => a.Eur(a.Result)); + + public decimal OpenResultEur => Positions.Sum(p => p.ResultEur); + + public static async Task LoadAsync(AppServices services, IClock clock, TimeZoneInfo zone, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(services); + var ledger = services.Trading?.Ledger ?? new Ledger(services.Db, clock); + var reconciler = services.Trading?.Reconciler ?? new Reconciler(services.Db, clock, ledger); + var fx = await new FxStore(services.Db, clock).LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false); + var rate = fx?.Rate ?? 0m; + + var (accounts, instruments, trades, orders, residues) = await services.Db.ReadAsync(async s => + { + var a = await s.QueryAsync("SELECT id, name, broker, environment, base_currency FROM accounts ORDER BY broker DESC, created_at", + r => (Id: r.Id("id"), Name: r.Text("name"), Broker: r.Text("broker"), Environment: r.Text("environment"), Currency: r.Text("base_currency"))).ConfigureAwait(false); + var i = await s.QueryAsync("SELECT id, symbol, name, quote_currency FROM instruments", + r => (Id: r.Id("id"), Symbol: r.Text("symbol"), Name: r.TextOrNull("name"), Quote: r.TextOrNull("quote_currency"))).ConfigureAwait(false); + var t = await s.QueryAsync("SELECT account_id, realized, fees FROM trades", r => (Account: r.Id("account_id"), Realized: r.Money("realized"), Fees: r.Money("fees"))) + .ConfigureAwait(false); + var o = await s.QueryAsync( + "SELECT account_id, instrument_id, side, order_type, purpose, quantity, filled_quantity, limit_price, stop_price, time_in_force, step, created_at, updated_at FROM orders " + + "WHERE status IN ('created', 'submitted', 'partially_filled') ORDER BY created_at, id", + r => new OpenOrder(r.Id("account_id"), r.Id("instrument_id"), r.Text("side"), r.Text("order_type"), r.TextOrNull("purpose") ?? "entry", r.Money("quantity"), + r.MoneyOrNull("filled_quantity") ?? 0m, r.MoneyOrNull("limit_price"), r.MoneyOrNull("stop_price"), r.TextOrNull("time_in_force") ?? "day", + r.IsNull("step") ? null : (int)r.Number("step"), r.Moment("created_at"), r.Moment("updated_at"))).ConfigureAwait(false); + var res = await s.QueryAsync("SELECT account_id, instrument_id, quantity, value, currency, created_at FROM residues ORDER BY created_at DESC", + r => (Account: r.Id("account_id"), Instrument: r.Id("instrument_id"), Quantity: r.Money("quantity"), Value: r.Money("value"), Currency: r.Text("currency"), + At: r.Moment("created_at"))).ConfigureAwait(false); + return (a, i.ToDictionary(x => x.Id), t, o, res); + }, cancellationToken).ConfigureAwait(false); + + var world = accounts.Any(a => TradingEnvironments.World(a.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated; + accounts = accounts.Where(a => TradingEnvironments.World(a.Environment) == world).ToList(); + var shown = accounts.Select(a => a.Id).ToHashSet(); + var equities = (await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false)).Where(e => shown.Contains(e.AccountId)).ToList(); + var positions = (await ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false)).Where(p => shown.Contains(p.AccountId)).ToList(); + + var rates = accounts.ToDictionary(a => a.Id, a => a.Currency == "USD" ? rate : 1m); + decimal Eur(Guid account, decimal amount) => rates[account] is var r && r > 0m && r != 1m ? amount / r : amount; + var currencies = accounts.ToDictionary(a => a.Id, a => a.Currency); + var rows = positions + .Select(p => + { + var instrument = instruments.GetValueOrDefault(p.InstrumentId); + var value = Math.Round(p.Value, 2, MidpointRounding.AwayFromZero); + return (Native: value, Row: new PositionRow(p.AccountId, accounts.First(a => a.Id == p.AccountId).Broker, instrument.Symbol ?? "?", instrument.Name ?? "", p.Strategy, + p.Quantity, p.AveragePrice, p.LastPrice ?? p.AveragePrice, p.StopPrice, instrument.Quote ?? currencies[p.AccountId], p.OpenedAt, + Math.Round(Eur(p.AccountId, value), 2, MidpointRounding.AwayFromZero), Math.Round(Eur(p.AccountId, p.Unrealized), 2, MidpointRounding.AwayFromZero))); + }) + .OrderByDescending(r => r.Row.ValueEur) + .ToList(); + + var cards = new List(); + foreach (var a in accounts) + { + var mine = equities.Where(e => e.AccountId == a.Id).ToList(); + var held = positions.Where(p => p.AccountId == a.Id).ToList(); + var valued = rows.Where(r => r.Row.AccountId == a.Id).ToList(); + var state = await reconciler.StateAsync(a.Id, cancellationToken).ConfigureAwait(false); + cards.Add(new AccountCard(a.Id, a.Name, a.Broker, a.Environment, a.Currency, mine.Sum(e => e.Cash), valued.Sum(r => r.Native), valued.Sum(r => r.Row.ValueEur), + held.Select(p => p.InstrumentId).Distinct().Count(), trades.Where(t => t.Account == a.Id).Sum(t => t.Realized), held.Sum(p => p.Unrealized), + trades.Where(t => t.Account == a.Id).Sum(t => t.Fees), mine.Sum(e => e.Flows), state, rates[a.Id])); + } + + var byId = cards.ToDictionary(c => c.Id); + var market = MarketState(services.MarketData?.UsCalendar, clock.UtcNow); + var (pending, others, alpacaStops) = PendingRows(orders.Where(o => shown.Contains(o.Account)).ToList(), byId, instruments.ToDictionary(i => i.Key, i => i.Value.Symbol), + positions, market.Open, market.Next, clock.UtcNow, zone); + + var slices = Strategies.Base.Select(b => new StrategySlice(Strategies.Label(b.Name, withMarket: true), "var(--s-" + b.Name.Replace('_', '-') + ")", + rows.Where(r => r.Row.Strategy == b.Name).Sum(r => r.Row.ValueEur))).ToList(); + decimal? fxEffect = null; + if (cards.Count > 0) + { + fxEffect = await services.Db.ReadAsync(s => s.FirstOrDefaultAsync( + "SELECT fx_effect FROM equity_snapshots WHERE scope = 'total' AND world = @w ORDER BY taken_at DESC LIMIT 1", r => r.MoneyOrNull("fx_effect"), ("w", world)), + cancellationToken).ConfigureAwait(false); + } + + var residueRows = residues.Where(r => shown.Contains(r.Account)) + .Select(r => new ResidueRow(byId[r.Account].Short, instruments.GetValueOrDefault(r.Instrument).Symbol ?? "?", r.Quantity, r.Value, r.Currency, r.At)).ToList(); + return new AccountsView(cards, rows.Select(r => r.Row).ToList(), pending, others, alpacaStops, residueRows, slices, fx?.Rate, fx?.Date, fxEffect, market.Open, market.Next); + } + + /// The positions as CSV for a spreadsheet: semicolons, dot decimals, one row per position. + public string Csv(string? broker) + { + var text = new StringBuilder("strumento;nome;conto;strategia;quantita;prezzo_medio;prezzo_ora;valuta;valore_eur;risultato_eur;stop;aperta_il\n"); + foreach (var p in Positions.Where(p => broker is null || p.Broker == broker)) + { + text.Append(string.Join(';', Clean(p.Symbol), Clean(p.Name), p.Broker, p.Strategy, Number(p.Quantity), Number(p.Average), Number(p.Last), p.Currency, + Number(Math.Round(p.ValueEur, 2)), Number(Math.Round(p.ResultEur, 2)), p.Stop is { } stop ? Number(stop) : "", + p.OpenedAt.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture))).Append('\n'); + } + + return text.ToString(); + + static string Number(decimal value) => value.ToString(CultureInfo.InvariantCulture); + + static string Clean(string value) => value.Replace(';', ',').Replace('\n', ' '); + } + + private sealed record OpenOrder(Guid Account, Guid Instrument, string Side, string Kind, string Purpose, decimal Quantity, decimal Filled, decimal? Limit, decimal? Stop, + string Tif, int? Step, DateTimeOffset CreatedAt, DateTimeOffset UpdatedAt); + + private static (List Rows, int Others, bool AlpacaStops) PendingRows(List orders, Dictionary accounts, Dictionary symbols, + IReadOnlyList positions, bool marketOpen, DateTimeOffset marketNext, DateTimeOffset now, TimeZoneInfo zone) + { + var rows = new List(); + var others = 0; + foreach (var o in orders.Where(o => o.Purpose != "stop")) + { + others++; + var account = accounts[o.Account]; + var verb = o.Side == "buy" ? "Compra" : "Vendi"; + var level = o.Limit is { } limit ? Format.Money(limit, account.Currency) : "a mercato"; + var status = o.Step is { } step && o.Kind == "limit" ? $"Passo {Math.Min(step + 1, 4)} di 4, dalle {Local(o.CreatedAt, zone)}" : "In corso dalle " + Local(o.CreatedAt, zone); + rows.Add(new PendingRow($"{verb} {Format.Quantity(o.Quantity - o.Filled)}", symbols.GetValueOrDefault(o.Instrument) ?? "?", account.Short, level, status, false)); + } + + var stops = orders.Where(o => o.Purpose == "stop").ToList(); + foreach (var o in stops.Where(o => accounts[o.Account].Broker != Venues.Alpaca).OrderByDescending(o => (o.Quantity - o.Filled) * (o.Stop ?? 0m))) + { + var account = accounts[o.Account]; + var local = TimeZoneInfo.ConvertTime(o.UpdatedAt, zone); + var status = local.Date == TimeZoneInfo.ConvertTime(now, zone).Date && o.UpdatedAt > o.CreatedAt + ? "Attivo, aggiornato oggi alle " + local.ToString("HH:mm", CultureInfo.InvariantCulture) + : "Attivo dal " + DayMonth(TimeZoneInfo.ConvertTime(o.CreatedAt, zone)); + rows.Add(new PendingRow("Vendi " + Format.Quantity(o.Quantity - o.Filled), symbols.GetValueOrDefault(o.Instrument) ?? "?", account.Short, + o.Stop is { } stop ? Format.Money(stop, account.Currency, decimals: StopDecimals(stop)) : "", status, false)); + } + + var alpaca = stops.Where(o => accounts[o.Account].Broker == Venues.Alpaca).ToList(); + var alpacaHeld = positions.Where(p => accounts.TryGetValue(p.AccountId, out var a) && a.Broker == Venues.Alpaca && p.StopPrice is not null).ToList(); + var gtc = alpaca.Count(o => o.Tif == "gtc"); + var fractions = alpacaHeld.Count(p => p.Quantity != decimal.Truncate(p.Quantity)); + if (gtc > 0) + { + rows.Add(new PendingRow(gtc == 1 ? "1 stop permanente" : $"{gtc} stop permanenti", "sulle azioni intere", "Alpaca", "vedi tabella sopra", gtc == 1 ? "Attivo" : "Attivi", false)); + } + + if (fractions > 0) + { + var opens = Local(marketNext, zone); + rows.Add(new PendingRow(fractions == 1 ? "1 stop giornaliero" : $"{fractions} stop giornalieri", "sulle frazioni di azione", "Alpaca", "vedi tabella sopra", + marketOpen ? "Attivi fino alla chiusura delle " + opens : "In coda per l'apertura delle " + opens, !marketOpen)); + } + + return (rows, others, gtc > 0 || fractions > 0); + } + + /// Whether the US market is open now, and its next close (open) or next open (closed). + public static (bool Open, DateTimeOffset Next) MarketState(IMarketCalendar? calendar, DateTimeOffset now) + { + var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(now, Zones.NewYork).DateTime); + foreach (var useCalendar in new[] { true, false }) + { + for (var d = -1; d <= 8; d++) + { + var day = today.AddDays(d); + var session = useCalendar ? calendar?.SessionOn(day) : Regular(day); + if (session is null) + { + continue; + } + + if (now >= session.OpenUtc && now < session.CloseUtc) + { + return (true, session.CloseUtc); + } + + if (session.OpenUtc > now) + { + return (false, session.OpenUtc); + } + } + } + + return (false, now); + } + + /// A regular session, 9:30 to 16:00 in New York on weekdays: used only when the broker's calendar is not there yet. + private static MarketSession? Regular(DateOnly day) + { + if (day.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday) + { + return null; + } + + DateTimeOffset At(int hour, int minute) + { + var local = day.ToDateTime(new TimeOnly(hour, minute)); + return new DateTimeOffset(local, Zones.NewYork.GetUtcOffset(local)).ToUniversalTime(); + } + + return new MarketSession(day, At(9, 30), At(16, 0)); + } + + private static string Local(DateTimeOffset moment, TimeZoneInfo zone) => TimeZoneInfo.ConvertTime(moment, zone).ToString("HH:mm", CultureInfo.InvariantCulture); + + /// Stops of a thousand or more without cents when they are round (66.180 €), the others with cents (166,00 $). + public static int StopDecimals(decimal stop) => stop >= 1000m && stop == decimal.Truncate(stop) ? 0 : 2; + + public static string DayMonth(DateTimeOffset local) + { + var text = Format.LongDate(DateOnly.FromDateTime(local.DateTime)); + return text[..text.LastIndexOf(' ')]; + } +} diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs index 24f41f7..cf6e46f 100644 --- a/src/Anubis.Server/AnubisHost.cs +++ b/src/Anubis.Server/AnubisHost.cs @@ -387,6 +387,15 @@ internal sealed partial class AnubisHost( Wake(); } + /// Stops and rebuilds the services, so that new broker keys take effect: a few seconds of "avvio". + internal async Task RestartServicesAsync(CancellationToken cancellationToken) + { + using (await ExclusiveAsync(cancellationToken).ConfigureAwait(false)) + { + await ResetAsync().ConfigureAwait(false); + } + } + /// /// Market data needs the network: off in demo mode (SPEC 13.7), when ANUBIS_MARKET_DATA is off, and /// in tests unless they bring their own fake network. diff --git a/src/Anubis.Server/Assets/app.css b/src/Anubis.Server/Assets/app.css index d040a84..4d3bab2 100644 --- a/src/Anubis.Server/Assets/app.css +++ b/src/Anubis.Server/Assets/app.css @@ -325,6 +325,67 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we .chart-table summary { color: var(--link); cursor: pointer; } .chart-table .table-wrap { max-height: 280px; overflow: auto; margin-top: 8px; } +/* ---- Conti e posizioni ---- */ +.muted { color: var(--text-3); font-weight: 400; } +.attention { color: var(--attention); } +.panel-head { display: flex; align-items: center; justify-content: space-between; gap: 12px 16px; flex-wrap: wrap; margin-bottom: 12px; } +.panel-head h2 { margin: 0; } +.panel-tools { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; } +.totals { padding: 24px 28px; } +.totals-cells { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; } +.total-value { font-size: 30px; line-height: 36px; font-weight: 650; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; } +.cell-note { color: var(--text-3); font-size: 13px; } +.split-bar { display: flex; gap: 3px; height: 12px; margin-top: 24px; } +.split-bar span { border-radius: 3px; min-width: 3px; } +.split-bar.slim { height: 12px; margin: 16px 0 12px; } +.split-legend { list-style: none; display: flex; flex-wrap: wrap; gap: 6px 28px; margin: 12px 0 0; padding: 0; color: var(--text-2); font-size: 13.5px; } +.split-legend li { display: inline-flex; align-items: center; gap: 8px; } +.split-legend strong { color: var(--text); font-weight: 600; } +.swatch { display: inline-block; width: 11px; height: 11px; border-radius: 2px; flex: none; margin-right: 8px; vertical-align: -1px; } +.swatch.round { width: 8px; height: 8px; border-radius: 50%; } +.split-legend .swatch { margin-right: 0; } +.account-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(380px, 1fr)); gap: 20px; } +.account { display: flex; flex-direction: column; padding: 22px 26px; } +.account-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; } +.account-head h2 { display: flex; align-items: center; gap: 10px; } +.tag { padding: 2px 8px; border-radius: 6px; background: var(--surface-2); color: var(--text-2); font-size: 13px; font-weight: 500; line-height: 20px; } +.link-state { display: inline-flex; align-items: center; gap: 8px; color: var(--text-2); font-size: 13.5px; } +.link-state.down .dot { background: var(--loss); } +.account-value { display: flex; align-items: baseline; gap: 14px; flex-wrap: wrap; margin: 14px 0 12px; } +.account-equity { font-size: 32px; line-height: 40px; font-weight: 650; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; } +.account-native, .native { color: var(--text-3); font-size: 13.5px; font-weight: 400; } +.native { margin-left: 0.35em; } +.account-lines { display: grid; grid-template-columns: minmax(0, 1fr) auto; margin: 0; font-variant-numeric: tabular-nums; } +.account-lines dt, .account-lines dd { padding: 9px 0; border-top: 1px solid var(--rule-inner); margin: 0; } +.account-lines dt { color: var(--text-2); } +.account-lines dd { text-align: right; } +.account-lines strong { font-weight: 600; } +.account-facts { list-style: none; margin: 16px 0 0; padding: 12px 16px; border-radius: 10px; background: var(--surface-2); display: flex; flex-direction: column; gap: 6px; font-size: 13.5px; color: var(--text-2); } +.account-facts li { display: flex; align-items: flex-start; gap: 10px; } +.account-facts .icon { margin-top: 2px; color: var(--text-3); } +.account-facts .loss .icon, .account-facts .attention .icon { color: inherit; } +.prudent { margin-top: 16px; } +.prudent > div { display: flex; flex-direction: column; gap: 8px; } +.differences { margin: 0; padding-left: 18px; } +.choices { display: flex; gap: 8px; flex-wrap: wrap; } +.choices form { margin: 0; } +.positions th[scope="row"] { font-weight: 400; text-align: left; white-space: nowrap; } +.positions th[scope="row"] strong { font-weight: 650; } +.table tbody tr:last-child td, .table tbody tr:last-child th { border-bottom: 0; } +.table tfoot th, .table tfoot td { padding: 12px 12px 4px 0; border-top: 2px solid var(--text); text-align: left; } +.table tfoot .num { text-align: right; } +.table th[scope="row"] { padding: 10px 12px 10px 0; border-bottom: 1px solid var(--rule-inner); vertical-align: top; } +.pending th[scope="row"], .positions th[scope="row"] { color: var(--text); } +.pending th[scope="row"] { font-weight: 400; text-align: left; } +.pending th[scope="row"] strong { font-weight: 650; } +.order-state { display: inline-flex; align-items: center; gap: 8px; } +.order-state .icon { color: var(--text-3); } +.aside { margin-top: 16px; padding: 12px 16px; border-radius: 10px; background: var(--surface-2); color: var(--text-2); font-size: 13.5px; } +.currency-lines { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 6px 16px; margin: 0 0 12px; font-variant-numeric: tabular-nums; } +.currency-lines dt { display: flex; align-items: center; color: var(--text-2); } +.currency-lines dd { margin: 0; text-align: right; } +.fx-warning { margin-top: 16px; } + /* ---- Service pages ---- */ .service { min-height: 100vh; display: flex; justify-content: center; padding: 48px 16px; } .service-box { width: 100%; max-width: 720px; display: flex; flex-direction: column; gap: 16px; } @@ -362,6 +423,16 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we .statement { font-size: 18px; line-height: 26px; margin-top: 12px; } .columns { grid-template-columns: 1fr; } .row { grid-template-columns: 1fr; } + .totals { padding: 18px; } + .totals-cells { grid-template-columns: 1fr 1fr; gap: 14px; } + .total-value { font-size: 22px; line-height: 28px; } + .split-legend { gap: 6px 16px; } + .account-grid { grid-template-columns: 1fr; gap: 14px; } + .account { padding: 18px; } + .account-equity { font-size: 28px; line-height: 34px; } + .positions .wide { display: none; } + .account-value .cell-change { display: inline-flex; flex-basis: 100%; } + .panel-tools { width: 100%; justify-content: space-between; } .facts { grid-template-columns: 1fr; gap: 2px; } .facts dd { margin-bottom: 8px; } .bottombar { diff --git a/src/Anubis.Server/Components/Icon.razor b/src/Anubis.Server/Components/Icon.razor index 6217352..1de3da8 100644 --- a/src/Anubis.Server/Components/Icon.razor +++ b/src/Anubis.Server/Components/Icon.razor @@ -35,6 +35,9 @@ case "dots": break; + case "download": + + break; case "collapse": break; diff --git a/src/Anubis.Server/Components/Pages/Conti.razor b/src/Anubis.Server/Components/Pages/Conti.razor index e171572..a93ed04 100644 --- a/src/Anubis.Server/Components/Pages/Conti.razor +++ b/src/Anubis.Server/Components/Pages/Conti.razor @@ -1,5 +1,413 @@ +@inherits LoadedComponent @page "/conti" +@inject AnubisHost Host +@inject ShellData Shell +@inject IClock Clock +@using Anubis.Trading +@using Anubis.Data Conti e posizioni · Anubis -Conti, posizioni e ordini arrivano con la contabilità: lì aggiungerai le chiavi dei conti di prova e vedrai patrimonio, liquidità e commissioni di ciascuno. +@{ + var v = _view; + var c = _currency; +} +@if (!v.HasAccounts) +{ + Il bot crea da solo i due simulatori interni, OKX e Alpaca, al primo avvio del motore di trading. I conti di prova dei broker compaiono quando ne aggiungi le chiavi in Impostazioni. +} +else +{ + @if (_message is { } message) + { +

@message

+ } + + var shares = Format.Shares([.. v.Slices.Select(s => s.Eur), v.CashEur]); + var winners = v.Positions.Count(p => p.ResultEur >= 0); +
+
+
+ Totale dei conti + @Shell.Money(v.TotalEur, c) + @Shell.Money(v.ResultEur, c, withSign: true) dall'avvio +
+
+ Investito + @Shell.Money(v.InvestedEur, c) + @Format.Percent(Part(v.InvestedEur, v.TotalEur)) del totale +
+
+ Liquidità + @Shell.Money(v.CashEur, c) + @Format.Percent(Part(v.CashEur, v.TotalEur)) del totale +
+
+ Risultato delle posizioni aperte + @Shell.Money(v.OpenResultEur, c, withSign: true) + @(v.Positions.Count == 0 ? "Nessuna posizione aperta" : $"{winners} in guadagno, {v.Positions.Count - winners} in perdita") +
+
+ +
    + @for (var i = 0; i < v.Slices.Count; i++) + { +
  • @v.Slices[i].Label @Format.Percent(shares[i])
  • + } +
  • Liquidità @Format.Percent(shares[^1])
  • +
+
+ + + + var shownPositions = v.Positions.Where(p => _filter is null || p.Broker == _filter).ToList(); +
+
+

Posizioni aperte

+
+ + Esporta CSV +
+
+ @if (shownPositions.Count == 0) + { +

Nessuna posizione aperta@(_filter is null ? "" : " su questo conto").

+ } + else + { +
+ + + + + + + + + + + + + + + + + @foreach (var p in shownPositions) + { + var gain = p.ResultEur >= 0; + + + + + + + + + + + + + } + + + + + + + + + + +
StrumentoContoStrategiaQuantitàPrezzo medioPrezzo oraValoreRisultatoStopAperta da
@p.Symbol @p.Name@(p.Broker == Venues.Alpaca ? "Alpaca" : "OKX")@Strategies.Label(p.Strategy)@Format.Quantity(p.Quantity)@Format.Money(p.Average, p.Currency)@Format.Money(p.Last, p.Currency)@Shell.Money(p.ValueEur, c)@Shell.Money(p.ResultEur, c, withSign: true) (@Format.Percent(p.Percent, 2, withSign: true))@(p.Stop is { } stop ? Format.Money(stop, p.Currency, decimals: AccountsView.StopDecimals(stop)) : "—")@Age(p.OpenedAt)
Totale@Shell.Money(shownPositions.Sum(p => p.ValueEur), c)@Shell.Money(shownPositions.Sum(p => p.ResultEur), c, withSign: true)
+
+ } +
+ +
+
+
+

Ordini in attesa

+ @(v.PendingOthers == 0 ? (v.Pending.Count == 0 ? "Nessun ordine aperto" : "Solo stop di protezione: nessun acquisto in coda") : $"{v.PendingOthers} {(v.PendingOthers == 1 ? "ordine" : "ordini")} in corso oltre agli stop") +
+ @if (v.Pending.Count > 0) + { +
+ + + + @foreach (var o in v.Pending) + { + + + + + + + } + +
OrdineDoveScatta aStato
@o.Action @o.Subject@o.Where@o.Level@if (o.Waiting) {} else {}@o.Status
+
+ } + @if (v.AlpacaStops) + { +

Le azioni intere hanno uno stop permanente sul broker, che resta attivo anche a bot spento. Sulle frazioni il broker accetta solo ordini che valgono un giorno: quelli li rimetto a ogni apertura e, a mercato chiuso, li sorveglio io.

+ } +
+ +
+

In quale valuta sono i soldi

+ @{ + var dollars = v.Accounts.Where(a => a.Currency == "USD").Sum(a => a.Eur(a.Equity)); + var euros = v.TotalEur - dollars; + var parts = Format.Shares([dollars, euros]); + } + +
+
Dollari (conto Alpaca)
@Shell.Money(dollars, c) @Format.Percent(parts[0])
+
Euro e crypto (conto OKX)
@Shell.Money(euros, c) @Format.Percent(parts[1])
+
+

@RateText(v)@(v.FxEffect is { } fx && fx != 0 ? $" Effetto del cambio sul risultato in euro: {Format.Money(fx, "EUR", withSign: true)}." : "")

+ @if (dollars > 0) + { +

Se il dollaro perde il 5% sull'euro, il totale scende di circa @Format.Money(Math.Round(dollars * 0.05m), "EUR", decimals: 0) anche a prezzi fermi.

+ } +
+
+ + @if (v.Residues.Count > 0) + { +
+
+

Residui sotto il minimo vendibile

+ Restano sul conto ma non sono più del bot: tolti dal registro al valore di mercato +
+
+ + + + @foreach (var r in v.Residues) + { + + } + +
StrumentoContoQuantitàValoreDal
@r.Symbol@r.Broker@Format.Quantity(r.Quantity)@Format.Money(r.Value, r.Currency)@Format.ShortDate(r.At, Shell.Now, Shell.Zone, withTime: false)
+
+
+ } +} + +@code { + private AccountsView _view = null!; + private string _currency = "EUR"; + private string? _filter; + private string? _message; + private bool _ok; + private Dictionary? _latency; + + [CascadingParameter] + public HttpContext? HttpContext { get; set; } + + [SupplyParameterFromQuery(Name = "conto")] + public string? Conto { get; set; } + + [SupplyParameterFromQuery(Name = "ok")] + public string? Ok { get; set; } + + [SupplyParameterFromQuery(Name = "errore")] + public string? Errore { get; set; } + + protected override async Task LoadAsync() + { + var ct = HttpContext?.RequestAborted ?? CancellationToken.None; + var services = Host.Services!; + _currency = Shell.Effective((await services.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value); + _view = await AccountsView.LoadAsync(services, Clock, Shell.Zone, ct); + _filter = Conto is Venues.Okx or Venues.Alpaca ? Conto : null; + (_message, _ok) = (Ok, Errore) switch + { + ("allinea", _) => ("Fatto: il registro ha preso i numeri del conto e il conto è tornato normale.", true), + ("escludi", _) => ("Fatto: la differenza resta fuori dal registro e il conto è tornato normale.", true), + (_, "motore") => ("Il motore di trading non è attivo: riprova tra poco.", false), + (_, "chiave") => ("Una chiave che permette i prelievi non si allinea: va sostituita in Impostazioni.", false), + (_, { }) => ("Non è stato possibile completare la scelta: riprova.", false), + _ => (null, false), + }; + using var aggregates = Shell.Aggregates(); + if (aggregates is not null) + { + var names = aggregates.RootElement.GetProperty("conti").EnumerateArray().Select(x => x.GetProperty("risposta_ms").GetInt32()).ToList(); + _latency = _view.Accounts.Select((a, i) => (a.Id, i)).Where(x => x.i < names.Count).ToDictionary(x => x.Id, x => names[x.i]); + } + } + + private string Connection(AccountCard a) + { + if (a.State.LastOutcome == ReconcileOutcomes.Unreachable) + { + return "Il broker non risponde"; + } + + if (_latency?.GetValueOrDefault(a.Id) is > 0 and var ms) + { + return $"Connesso, risposta in {ms} ms"; + } + + return a.Environment == TradingEnvironments.Simulation ? "Attivo, nel simulatore" : "Connesso"; + } + + private static string Holdings(AccountCard a) => (a.Broker, a.Holdings) switch + { + (_, 0) => "nulla", + (Venues.Alpaca, 1) => "1 azione", + (Venues.Alpaca, var n) => $"{n} azioni", + (_, 1) => "1 moneta", + (_, var n) => $"{n} monete", + }; + + private static string RateText(AccountsView v, bool withSource = true) => v.UsdRate is { } rate + ? $"Cambio usato: 1 € = {Format.Quantity(rate)} $" + (withSource ? $" (BCE, {AccountsView.DayMonth(new DateTimeOffset(v.RateDay!.Value.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero))})." : ".") + : "Manca ancora il cambio euro/dollaro della BCE: i dollari restano nella loro valuta."; + + private static decimal Part(decimal part, decimal total) => total == 0 ? 0 : part / total * 100m; + + private static string Css(decimal percent) => percent.ToString("0.###", CultureInfo.InvariantCulture); + + private string Time(DateTimeOffset? moment) => moment is { } m ? TimeZoneInfo.ConvertTime(m, Shell.Zone).ToString("HH:mm", CultureInfo.InvariantCulture) : "—"; + + private string Age(DateTimeOffset opened) + { + var days = (int)Math.Floor((Shell.Now - opened).TotalDays); + return days switch + { + < 1 => "oggi", + 1 => "1 giorno", + _ => $"{days} giorni", + }; + } +} diff --git a/src/Anubis.Server/Components/Pages/Impostazioni.razor b/src/Anubis.Server/Components/Pages/Impostazioni.razor index 091ecf4..885e38d 100644 --- a/src/Anubis.Server/Components/Pages/Impostazioni.razor +++ b/src/Anubis.Server/Components/Pages/Impostazioni.razor @@ -4,10 +4,12 @@ @inject ShellData Shell @inject SecondFactorDrafts Drafts @inject Anubis.Core.IClock Clock +@using Anubis.Data +@using Anubis.Trading Impostazioni · Anubis -@* First part of SPEC 13.5: appearance, security, system. The other sections arrive with their phases. *@ +@* SPEC 13.5: appearance, accounts and keys, data, security, system. The other sections arrive with their phases. *@ @if (Ok is { } ok) {

@(ok switch @@ -16,6 +18,9 @@ "due-fattori" => "Secondo fattore attivato.", "due-fattori-tolti" => "Secondo fattore disattivato.", "salvataggio" => "Salvataggio fatto.", + "chiavi" => "Chiavi verificate e salvate: possono fare ordini e non possono prelevare. Il motore è ripartito e le usa.", + "chiavi-tolte" => "Chiavi tolte: quel conto torna al simulatore interno per le strategie che non hanno ancora storia sul conto di prova.", + "capitale" => "Capitale affidato aggiornato e diviso tra le strategie.", _ => "Fatto.", })

} @@ -25,7 +30,7 @@ }
@@ -56,6 +61,80 @@

Gli importi in dollari usano il cambio del giorno, che arriva con i dati di mercato. Fino ad allora restano in euro.

+
+

Conti e chiavi

+

In questa fase uso solo denaro finto: il simulatore interno è sempre acceso e, con le chiavi dei conti di prova, le strategie passano ai conti di prova dei broker. Le chiavi di conti veri non servono e non vanno inserite.

+ @foreach (var b in _brokers) + { +

@b.Title

+
+ @foreach (var k in b.Keys) + { +
@k.Label
@KeyState(k.Status)
+ } + @if (b.State is { KeyCheckedAt: { } checkedAt } state) + { +
Permessi
+
@(state.KeyCanWithdraw == true ? "Permette i prelievi: va sostituita, intanto niente nuovi acquisti" : state.KeyCanTrade == true ? "Legge e fa ordini, nessun prelievo" : "Solo lettura") (verificati @Inline(Format.ShortDate(checkedAt, Shell.Now, Shell.Zone)))
+ } +
+ @if (Shell.IsDemo) + { +

Nella modalità dimostrativa chiavi e capitale non si cambiano.

+ } + else if (b.Keys.Any(k => k.Status.FromEnvironment)) + { +

Le chiavi arrivano dalle variabili d'ambiente e valgono più di quelle salvate qui: si cambiano nella configurazione del container.

+ } + else + { +
+ + @foreach (var k in b.Keys) + { + + + } + + +

Non le rimostro mai. Prima di salvarle chiedo al broker cosa possono fare: una chiave che permette i prelievi la rifiuto. Dopo il salvataggio il motore riparte da solo, in pochi secondi.

+ @if (b.Keys.Any(k => k.Status.IsSet)) + { +
+ } + } + +

Capitale affidato a @b.Short

+ @if (b.Entrusted is { } e) + { +

@Format.Money(e.AmountEur, "EUR")@(e.Currency == "EUR" ? "" : $", cioè {Format.Money(e.Amount, e.Currency)} al cambio di {Format.Quantity(e.FxRate)}"), deciso @Inline(Format.ShortDate(e.At, Shell.Now, Shell.Zone)) da @e.ChangedBy.

+ } + else + { +

Nessun capitale affidato: le strategie di @b.Short osservano soltanto.

+ } + @if (b.Strategies.Count > 0) + { +
    + @foreach (var s in b.Strategies) + { +
  • @Strategies.Label(s.Strategy, withMarket: true): quota @Format.Percent(s.Share * 100m, 0), capitale @Format.Money(s.Capital, s.Currency), liquidità @Format.Money(s.Cash, s.Currency)
  • + } +
+ } + @if (!Shell.IsDemo) + { +
+ + + + + +

Si divide tra le strategie del conto secondo le quote@(b.Broker == Venues.Alpaca ? ", in dollari al cambio BCE del giorno" : ""). Ridurlo non vende nulla: se una strategia ha investito più di quanto le resterebbe, aspetto che venda.

+ } + } +
+

Dati

@if (Host.Services!.MarketData is not { } market) @@ -217,6 +296,12 @@ @code { private readonly List _appearance = []; + private readonly List _brokers = []; + + private sealed record BrokerKey(string Name, string Label, SecretStatus Status); + + private sealed record BrokerSetup(string Broker, string Title, string Short, IReadOnlyList Keys, AccountState? State, EntrustedCapital? Entrusted, + IReadOnlyList Strategies); private IReadOnlyList _sources = []; private SettingValue _meetings = new(SettingsStore.CentralBankMeetings.Key, "", false, null); private List _history = []; @@ -244,6 +329,21 @@ _meetings = await services.Settings.GetAsync(SettingsStore.CentralBankMeetings.Key, ct); _sources = await new Anubis.Data.SourceStateStore(services.Db, Clock).ListAsync(ct); _backups = services.Backups.List(); + var ledger = new Ledger(services.Db, Clock); + var capital = new Capital(services.Db, Clock, ledger, new FxStore(services.Db, Clock)); + var reconciler = new Reconciler(services.Db, Clock, ledger); + foreach (var (broker, title, name) in new[] { (Venues.Okx, "OKX Europe · conto demo", "OKX"), (Venues.Alpaca, "Alpaca · conto di prova (paper)", "Alpaca") }) + { + var keys = new List(); + foreach (var (secret, label) in TradingService.KeyFields(broker)) + { + keys.Add(new BrokerKey(secret, label, await services.Secrets.StatusAsync(secret, ct))); + } + + var demoAccount = await services.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT id FROM accounts WHERE broker = @b AND environment = 'demo'", r => (Guid?)r.Id("id"), ("b", broker)), ct); + var state = demoAccount is { } id ? await reconciler.StateAsync(id, ct) : null; + _brokers.Add(new BrokerSetup(broker, title, name, keys, state, await capital.EntrustedAsync(broker, ct), await capital.StrategiesAsync(broker, ct))); + } var user = HttpContext!.User; _hasSecondFactor = CurrentUser.HasSecondFactor(user); if (!_hasSecondFactor && !Shell.IsDemo) @@ -262,9 +362,30 @@ "impostazione" => "Questa impostazione non si può cambiare così.", "riunioni" => "L'elenco delle riunioni non è valido: una riga per riunione, con FED o BCE e la data, per esempio «FED 2027-01-27».", "bot" => "Comando non ammesso nello stato attuale del bot.", + "motore" => "Il motore di trading non è attivo (modalità dimostrativa o ANUBIS_TRADING spento): qui non si cambia nulla.", + "conto" => "Conto sconosciuto.", + "ambiente" => "Le chiavi di questo conto arrivano dalle variabili d'ambiente: si cambiano nella configurazione del container.", + "chiavi-vuote" => "Servono tutti i campi della chiave.", + "chiavi-rifiutate" => "Il broker non ha accettato la chiave, o non ha risposto. Controlla di aver copiato la chiave del conto di prova e riprova. Non ho salvato nulla.", + "prelievo" => "Questa chiave permette i prelievi: non la salvo. Creane una senza il permesso di prelievo.", + "sola-lettura" => "Questa chiave può solo leggere: per lavorare sul conto di prova serve anche il permesso di fare ordini. Non l'ho salvata.", + "importo" => "Scrivi un importo in euro, per esempio 4000 o 1.500,50.", + "cambio" => "Manca ancora il cambio euro/dollaro della BCE: lo scarico ogni giorno, riprova più tardi.", + "capitale" => "Una strategia ha investito più di quanto le resterebbe: potrò ridurre il capitale quando avrà venduto.", _ => PasswordMessages.For(Errore), }; + private string KeyState(SecretStatus status) => status switch + { + { FromEnvironment: true } => "Dalle variabili d'ambiente", + { IsSet: true, UpdatedAt: { } at } => "Impostata " + Inline(Format.ShortDate(at, Shell.Now, Shell.Zone)), + { IsSet: true } => "Impostata", + _ => "Non impostata", + }; + + // "Oggi 08:20" inside a sentence reads "oggi 08:20". + private static string Inline(string text) => text.Length == 0 ? text : char.ToLowerInvariant(text[0]) + text[1..]; + private static string SourceName(string source) => source switch { "okx" => "OKX Europe (crypto)", diff --git a/src/Anubis.Server/Components/Pages/Panoramica.razor b/src/Anubis.Server/Components/Pages/Panoramica.razor index b6cf335..65f86ae 100644 --- a/src/Anubis.Server/Components/Pages/Panoramica.razor +++ b/src/Anubis.Server/Components/Pages/Panoramica.razor @@ -9,6 +9,10 @@ var o = _overview; var c = _currency; } +@if (!o.CapitalSet && !Shell.IsDemo) +{ +

Primo passo: decidi quanto capitale affidare al bot in Impostazioni, Conti e chiavi. Lì puoi anche inserire le chiavi dei conti di prova. Finché non c'è capitale, le strategie osservano soltanto.

+}
diff --git a/src/Anubis.Server/Endpoints.cs b/src/Anubis.Server/Endpoints.cs index ae96ff6..7ac0522 100644 --- a/src/Anubis.Server/Endpoints.cs +++ b/src/Anubis.Server/Endpoints.cs @@ -146,6 +146,16 @@ internal static partial class Endpoints return format == "md" ? Results.Text(report.ToMarkdown(), "text/markdown; charset=utf-8") : Results.Json(report, _json); }); + // The open positions of the Conti screen as CSV (SPEC 13.6), all accounts or one broker's. + api.MapGet("/conti/posizioni.csv", async (AnubisHost host, ShellData shell, IClock clock, string? conto, CancellationToken ct) => + { + var view = await AccountsView.LoadAsync(host.Services!, clock, shell.Zone, ct).ConfigureAwait(false); + var broker = conto is Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca ? conto : null; + var day = TimeZoneInfo.ConvertTime(clock.UtcNow, shell.Zone).ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); + return Results.File(System.Text.Encoding.UTF8.GetPreamble().Concat(System.Text.Encoding.UTF8.GetBytes(view.Csv(broker))).ToArray(), + "text/csv; charset=utf-8", $"anubis-posizioni-{day}.csv"); + }); + // The external sources and the live feed: what is on, what is off and why (SPEC 4.4). api.MapGet("/data/sources", async (AnubisHost host, IClock clock, CancellationToken ct) => { diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs index 9f05537..52969c2 100644 --- a/src/Anubis.Server/Forms.cs +++ b/src/Anubis.Server/Forms.cs @@ -30,6 +30,10 @@ internal static partial class Forms signed.MapPost("/impostazioni/{key}", SetSettingAsync); signed.MapPost("/bot/{command}", BotAsync); signed.MapPost("/salvataggio", BackupAsync); + signed.MapPost("/conti/{id:guid}/{choice}", ResolveAccountAsync); + signed.MapPost("/chiavi/{broker}", SaveKeysAsync); + signed.MapPost("/chiavi/{broker}/togli", RemoveKeysAsync); + signed.MapPost("/capitale/{broker}", SetCapitalAsync); } private static string Back(IFormCollection form, string fallback) @@ -172,6 +176,165 @@ internal static partial class Forms return Results.Redirect(ok ? back : With(back, "errore", "bot")); } + /// The user's choice for an account in prudent mode after the 15 minutes (SPEC 7.4): align or leave out. + private static async Task ResolveAccountAsync(Guid id, string choice, AnubisHost host, HttpContext context, CancellationToken ct) + { + if (choice is not ("allinea" or "escludi")) + { + return Results.Redirect("/conti?errore=scelta"); + } + + if (host.IsDemo || host.Services?.Trading is not { } trading || trading.ManagerOf(id) is not { } manager) + { + return Results.Redirect("/conti?errore=motore"); + } + + var state = await trading.Reconciler.StateAsync(id, ct).ConfigureAwait(false); + if (state.ModeReason == Anubis.Trading.Reconciler.KeyReason) + { + return Results.Redirect("/conti?errore=chiave"); + } + + await trading.Reconciler.ResolveAsync(manager, choice == "allinea" ? Anubis.Trading.ReconcileChoice.Align : Anubis.Trading.ReconcileChoice.Exclude, + context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false); + return Results.Redirect("/conti?ok=" + choice); + } + + /// + /// New practice keys for a broker (SPEC 13.5): asked to the broker first, kept only if they may trade and may not + /// withdraw (SPEC 2.2), saved encrypted, never shown again. The engine then restarts to use them. + /// + private static async Task SaveKeysAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) + { + const string back = "/impostazioni"; + if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca)) + { + return Results.Redirect(back + "?errore=conto#conti"); + } + + if (host.IsDemo || host.Services is not { Trading: { } trading } services) + { + return Results.Redirect(back + "?errore=motore#conti"); + } + + var fields = Anubis.Trading.TradingService.KeyFields(broker); + foreach (var (name, _) in fields) + { + if ((await services.Secrets.StatusAsync(name, ct).ConfigureAwait(false)).FromEnvironment) + { + return Results.Redirect(back + "?errore=ambiente#conti"); + } + } + + var values = fields.Select(f => form[f.Name].ToString().Trim()).ToList(); + if (values.Any(v => v.Length == 0 || v.Length > 512)) + { + return Results.Redirect(back + "?errore=chiavi-vuote#conti"); + } + + Anubis.Trading.KeyPermissions permissions; + try + { + permissions = await trading.TestKeysAsync(broker, values, ct).ConfigureAwait(false); + } + catch (Anubis.Trading.BrokerException) + { + return Results.Redirect(back + "?errore=chiavi-rifiutate#conti"); + } + + if (permissions.CanWithdraw) + { + return Results.Redirect(back + "?errore=prelievo#conti"); + } + + if (!permissions.CanTrade) + { + return Results.Redirect(back + "?errore=sola-lettura#conti"); + } + + var who = context.User.Identity?.Name ?? "utente"; + for (var i = 0; i < fields.Count; i++) + { + await services.Secrets.SetAsync(fields[i].Name, values[i], who, ct).ConfigureAwait(false); + } + + await host.RestartServicesAsync(ct).ConfigureAwait(false); + await WaitBrieflyAsync(host).ConfigureAwait(false); + return Results.Redirect(back + "?ok=chiavi#conti"); + } + + private static async Task RemoveKeysAsync(string broker, AnubisHost host, HttpContext context, CancellationToken ct) + { + const string back = "/impostazioni"; + if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca) || host.IsDemo || host.Services is not { } services) + { + return Results.Redirect(back + "?errore=conto#conti"); + } + + var who = context.User.Identity?.Name ?? "utente"; + foreach (var (name, _) in Anubis.Trading.TradingService.KeyFields(broker)) + { + await services.Secrets.RemoveAsync(name, who, ct).ConfigureAwait(false); + } + + await host.RestartServicesAsync(ct).ConfigureAwait(false); + await WaitBrieflyAsync(host).ConfigureAwait(false); + return Results.Redirect(back + "?ok=chiavi-tolte#conti"); + } + + /// The capital entrusted to a broker, in euro (SPEC 7.1, 8.6): only the user sets it. + private static async Task SetCapitalAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) + { + const string back = "/impostazioni"; + if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca)) + { + return Results.Redirect(back + "?errore=conto#conti"); + } + + if (host.IsDemo || host.Services?.Trading is not { } trading) + { + return Results.Redirect(back + "?errore=motore#conti"); + } + + if (ParseEuro(form["euro"].ToString()) is not { } amount || amount < 0m || amount > 100_000_000m) + { + return Results.Redirect(back + "?errore=importo#conti"); + } + + try + { + await trading.SetCapitalAsync(broker, amount, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false); + } + catch (Anubis.Trading.CapitalException ex) when (ex.Message.StartsWith("Manca il cambio", StringComparison.Ordinal)) + { + return Results.Redirect(back + "?errore=cambio#conti"); + } + catch (Anubis.Trading.CapitalException) + { + return Results.Redirect(back + "?errore=capitale#conti"); + } + + return Results.Redirect(back + "?ok=capitale#conti"); + } + + /// An amount as people type it: "1500", "1.500", "1500,50", "1.500,50", "1500.50". + internal static decimal? ParseEuro(string text) + { + var clean = (text ?? "").Replace(" ", "", StringComparison.Ordinal).Replace("€", "", StringComparison.Ordinal); + if (clean.Contains(',', StringComparison.Ordinal)) + { + clean = clean.Replace(".", "", StringComparison.Ordinal).Replace(',', '.'); + } + else if (clean.LastIndexOf('.') is var dot and >= 0 && clean.Length - dot - 1 == 3) + { + clean = clean.Replace(".", "", StringComparison.Ordinal); + } + + return decimal.TryParse(clean, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out var value) + ? Math.Round(value, 2, MidpointRounding.ToZero) + : null; + } + private static async Task BackupAsync(IFormCollection form, AnubisHost host, ILogger logger, CancellationToken ct) { var services = host.Services!; diff --git a/src/Anubis.Server/Overview.cs b/src/Anubis.Server/Overview.cs index b1e0ad1..8a0f0fc 100644 --- a/src/Anubis.Server/Overview.cs +++ b/src/Anubis.Server/Overview.cs @@ -1,9 +1,11 @@ using Anubis.Core; using Anubis.Db; +using Anubis.Trading; namespace Anubis.Server; -public sealed record EquityPoint(DateTimeOffset At, DateOnly Day, decimal Equity, decimal? Benchmark); +/// A point of the total: equity, the capital put in or taken out so far (cumulative) and the time-weighted index. +public sealed record EquityPoint(DateTimeOffset At, DateOnly Day, decimal Equity, decimal? Benchmark, decimal Flows = 0m, decimal? Twr = null); internal sealed record PeriodResult(string Label, decimal Amount, decimal Percent); @@ -11,7 +13,11 @@ internal sealed record NextMove(string Time, string Text); internal sealed record LastAction(string When, string Text); -/// The "Finora" and "Adesso e dopo" halves of the Panoramica (SPEC 13.2, 13.6), read from the database. +/// +/// The "Finora" and "Adesso e dopo" halves of the Panoramica (SPEC 13.2, 13.6), read from the database. One world +/// only, as on the Conti screen: real money when there is a real account, otherwise the simulated one. Results leave +/// out the capital put in or taken out (SPEC 7.5): the amount is net of flows, the percentage is time-weighted. +/// internal sealed record Overview( IReadOnlyList Points, IReadOnlyList Series, @@ -23,7 +29,8 @@ internal sealed record Overview( int PositionsWithoutStop, int OpenOrders, IReadOnlyList Next, - IReadOnlyList Last) + IReadOnlyList Last, + bool CapitalSet = true) { public static readonly IReadOnlyList<(string Key, string Label)> Periods = [("avvio", "Dall'avvio"), ("30", "30 giorni"), ("7", "7 giorni"), ("oggi", "Oggi")]; @@ -31,22 +38,29 @@ internal sealed record Overview( public static async Task LoadAsync(AppServices services, string period, DateTimeOffset now, TimeZoneInfo zone, CancellationToken cancellationToken) { - var (points, positions, withoutStop, orders, journal) = await services.Db.ReadAsync(async s => + var (points, positions, withoutStop, orders, journal, capitalSet) = await services.Db.ReadAsync(async s => { + var environments = await s.QueryAsync("SELECT environment FROM accounts", r => r.Text("environment")).ConfigureAwait(false); + var world = environments.Any(e => TradingEnvironments.World(e) == Worlds.Real) ? Worlds.Real : Worlds.Simulated; + var mine = string.Join(", ", new[] { TradingEnvironments.Simulation, TradingEnvironments.Demo, TradingEnvironments.Live }.Where(e => TradingEnvironments.World(e) == world).Select(e => "'" + e + "'")); var p = await s.QueryAsync( - "SELECT taken_at, equity, benchmark FROM equity_snapshots WHERE scope = 'total' ORDER BY taken_at", - r => (At: r.Moment("taken_at"), Equity: r.Money("equity"), Benchmark: r.MoneyOrNull("benchmark"))).ConfigureAwait(false); - var count = await s.CountAsync("SELECT COUNT(*) FROM positions").ConfigureAwait(false); - var noStop = await s.CountAsync("SELECT COUNT(*) FROM positions WHERE stop_price IS NULL").ConfigureAwait(false); - var open = await s.CountAsync("SELECT COUNT(*) FROM orders WHERE status IN ('new', 'submitted', 'accepted', 'partially_filled')").ConfigureAwait(false); + "SELECT taken_at, equity, benchmark, flows, twr_index FROM equity_snapshots WHERE scope = 'total' AND world = @w ORDER BY taken_at", + r => (At: r.Moment("taken_at"), Equity: r.Money("equity"), Benchmark: r.MoneyOrNull("benchmark"), Flows: r.MoneyOrNull("flows") ?? 0m, Twr: r.MoneyOrNull("twr_index")), + ("w", world)).ConfigureAwait(false); + var held = (await s.QueryAsync($"SELECT p.quantity, p.stop_price FROM positions p JOIN accounts a ON a.id = p.account_id WHERE a.environment IN ({mine})", + r => (Quantity: r.Money("quantity"), Stop: r.MoneyOrNull("stop_price"))).ConfigureAwait(false)).Where(x => x.Quantity > 0m).ToList(); + var open = await s.CountAsync( + $"SELECT COUNT(*) FROM orders o JOIN accounts a ON a.id = o.account_id WHERE a.environment IN ({mine}) " + + "AND o.status IN ('created', 'submitted', 'partially_filled') AND (o.purpose IS NULL OR o.purpose <> 'stop')").ConfigureAwait(false); var j = await s.QueryAsync("SELECT occurred_at, message FROM journal ORDER BY occurred_at DESC LIMIT 4", r => (At: r.Moment("occurred_at"), Text: r.Text("message"))).ConfigureAwait(false); - return (p, count, noStop, open, j); + var capital = await s.CountAsync("SELECT COUNT(*) FROM capital_changes").ConfigureAwait(false); + return (p, held.Count, held.Count(x => x.Stop is null), open, j, capital > 0); }, cancellationToken).ConfigureAwait(false); // One point per day: the last snapshot of each local day. var daily = points - .Select(p => new EquityPoint(p.At, DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(p.At, zone).DateTime), p.Equity, p.Benchmark)) + .Select(p => new EquityPoint(p.At, DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(p.At, zone).DateTime), p.Equity, p.Benchmark, p.Flows, p.Twr)) .GroupBy(p => p.Day) .Select(g => g.Last()) .ToList(); @@ -58,13 +72,19 @@ internal sealed record Overview( if (daily.Count == 0) { - return new Overview([], [], new PeriodResult("", 0, 0), default, 0, [], (int)positions, (int)withoutStop, (int)orders, next, last); + return new Overview([], [], new PeriodResult("", 0, 0), default, 0, [], (int)positions, (int)withoutStop, (int)orders, next, last, capitalSet); } var latest = daily[^1]; EquityPoint Since(int days) => daily.LastOrDefault(p => p.Day <= latest.Day.AddDays(-days)) ?? daily[0]; - PeriodResult Between(string label, EquityPoint start) => - new(label, latest.Equity - start.Equity, start.Equity == 0 ? 0 : (latest.Equity - start.Equity) / start.Equity * 100m); + PeriodResult Between(string label, EquityPoint start) + { + var amount = latest.Equity - start.Equity - (latest.Flows - start.Flows); + var basis = start.Equity + (latest.Flows - start.Flows); + var percent = start.Twr is > 0m && latest.Twr is { } twr ? (twr / start.Twr.Value - 1m) * 100m + : basis == 0 ? 0 : amount / basis * 100m; + return new PeriodResult(label, amount, percent); + } var start = period switch { @@ -80,6 +100,6 @@ internal sealed record Overview( cells.Add(new PeriodResult("Senza bot", lastBenchmark - firstBenchmark, (lastBenchmark - firstBenchmark) / firstBenchmark * 100m)); } - return new Overview(daily, series, Between("", start), start.Day, start.Equity, cells, (int)positions, (int)withoutStop, (int)orders, next, last); + return new Overview(daily, series, Between("", start), start.Day, start.Equity, cells, (int)positions, (int)withoutStop, (int)orders, next, last, capitalSet); } } diff --git a/src/Anubis/Demo/DemoMode.cs b/src/Anubis/Demo/DemoMode.cs index 567542b..8f8494d 100644 --- a/src/Anubis/Demo/DemoMode.cs +++ b/src/Anubis/Demo/DemoMode.cs @@ -12,12 +12,15 @@ namespace Anubis.Demo; /// Demo mode (SPEC 13.1, appendix F): a separate SQLite database in a new temporary folder, never the configured /// one (trap 27), filled with the rows of appendix F; the clock frozen at Friday 9 October 2026, 08:21 Italian /// time; no broker. Values that appendix F gives only as totals go to an aggregates file that only this mode reads. -/// Rows of tables that later phases create (closed trades, news, models) are loaded by those phases. +/// Rows of tables that later phases create (news, models) are loaded by those phases. ///
public static class DemoMode { public const string AggregatesFile = "demo-aggregates.json"; + /// The ECB rate of the demo's morning (F.2): one euro, 1,1601 dollars. + public const decimal UsdRate = 1.1601m; + /// "Adesso" in the demo: Friday 9 October 2026, 08:21 in Rome. public static readonly DateTimeOffset Now = new(2026, 10, 9, 8, 21, 0, TimeSpan.FromHours(2)); @@ -109,34 +112,64 @@ public static class DemoMode await s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, 'OKX Europe', 'okx', 'simulation', 'EUR', @t), (@id2, 'Alpaca', 'alpaca', 'demo', 'USD', @t)", cancellationToken, ("id", okx), ("id2", alpaca), ("t", now)).ConfigureAwait(false); - var strategies = new Dictionary + // F.2, F.3: capital in each account's currency, euro on OKX and dollars on Alpaca at the day's rate. + var strategies = new Dictionary { - ["Trend crypto"] = ("crypto_trend", okx, 4000m), - ["Momentum"] = ("equity_momentum", alpaca, 4500m), - ["Mean reversion"] = ("equity_meanrev", alpaca, 1500m), + ["Trend crypto"] = ("crypto_trend", okx, 4000m, 1905.10m, 1m), + ["Momentum"] = ("equity_momentum", alpaca, 5220.44m, 893.50m, 0.75m), + ["Mean reversion"] = ("equity_meanrev", alpaca, 1740.15m, 1236.71m, 0.25m), }; - foreach (var (name, account, capital) in strategies.Values) + var currencyOf = new Dictionary { [okx] = "EUR", [alpaca] = "USD" }; + foreach (var (name, account, capital, _, share) in strategies.Values) { - await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at) VALUES (@id, @n, @a, 'simulation', @c, @st, @t, @t)", - cancellationToken, ("id", ids.Next()), ("n", name), ("a", account), ("c", capital), ("st", new DbJson("{\"day\":58,\"of\":60}")), ("t", now)).ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, share, state, created_at, updated_at) VALUES (@id, @n, @a, 'simulation', @c, @sh, @st, @t, @t)", + cancellationToken, ("id", ids.Next()), ("n", name), ("a", account), ("c", capital), ("sh", share), ("st", new DbJson("{\"day\":58,\"of\":60}")), ("t", now)) + .ConfigureAwait(false); + } + + var started = now.AddDays(-60); + await s.ExecuteAsync("INSERT INTO fx_rates (id, base, quote, rate_date, rate, source, created_at) VALUES (@id, 'EUR', 'USD', @d, @r, 'ecb', @t)", + cancellationToken, ("id", ids.Next()), ("d", DateOnly.FromDateTime(Now.DateTime).ToString("yyyy-MM-dd", _it)), ("r", UsdRate), ("t", now.AddMinutes(-21))) + .ConfigureAwait(false); + foreach (var (broker, eur, currency, rate, amount) in new[] { ("okx", 4000m, "EUR", 1m, 4000m), ("alpaca", 6000m, "USD", UsdRate, 6960.59m) }) + { + await s.ExecuteAsync("INSERT INTO capital_changes (id, broker, amount_eur, currency, fx_rate, amount, changed_by, created_at) VALUES (@id, @b, @e, @c, @r, @a, 'demo', @t)", + cancellationToken, ("id", ids.Next()), ("b", broker), ("e", eur), ("c", currency), ("r", rate), ("a", amount), ("t", started)).ConfigureAwait(false); } // F.4: the ten open positions. + var held = new List<(string Symbol, Guid Instrument, Guid Account, string Strategy, decimal Quantity, decimal Average, decimal Stop, DateTimeOffset Opened)>(); foreach (var row in Csv("positions.csv").Skip(1)) { var symbol = row[0]; var crypto = symbol.Contains('/', StringComparison.Ordinal); var instrument = ids.Next(); - var (strategy, account, _) = strategies[row[3]]; + var (strategy, account, _, _, _) = strategies[row[3]]; + var opened = now.AddDays(-int.Parse(row[11], _it)); await s.ExecuteAsync("INSERT INTO instruments (id, venue, symbol, name, asset_class, quote_currency, created_at) VALUES (@id, @v, @s, @n, @c, @q, @t)", cancellationToken, ("id", instrument), ("v", crypto ? "okx" : "alpaca"), ("s", symbol), ("n", row[1]), ("c", crypto ? "crypto" : "equity"), ("q", crypto ? "EUR" : "USD"), ("t", now)).ConfigureAwait(false); await s.ExecuteAsync( "INSERT INTO positions (id, account_id, instrument_id, strategy, quantity, average_price, last_price, stop_price, opened_at, created_at, updated_at) VALUES (@id, @a, @i, @s, @q, @p, @l, @st, @o, @t, @t)", cancellationToken, ("id", ids.Next()), ("a", account), ("i", instrument), ("s", strategy), ("q", Number(row[4])), ("p", Number(row[5])), ("l", Number(row[6])), - ("st", Number(row[10])), ("o", now.AddDays(-int.Parse(row[11], _it))), ("t", now)).ConfigureAwait(false); + ("st", Number(row[10])), ("o", opened), ("t", now)).ConfigureAwait(false); + held.Add((symbol, instrument, account, strategy, Number(row[4]), Number(row[5]), Number(row[10]), opened)); } + // Each strategy's cash: the capital given at the start, less what its positions and past trades took. + foreach (var (name, account, capital, cash, _) in strategies.Values) + { + foreach (var (kind, amount, note) in new[] { ("capital", capital, "Capitale affidato"), ("buy", cash - capital, "Saldo di acquisti, vendite e commissioni") }) + { + await s.ExecuteAsync("INSERT INTO cash_ledger (id, account_id, strategy, currency, amount, kind, note, occurred_at, created_at) VALUES (@id, @a, @s, @c, @m, @k, @n, @at, @t)", + cancellationToken, ("id", ids.Next()), ("a", account), ("s", name), ("c", currencyOf[account]), ("m", amount), ("k", kind), ("n", note), + ("at", kind == "capital" ? started : now), ("t", now)).ConfigureAwait(false); + } + } + + await SeedTradesAsync(s, ids, strategies.Values.ToDictionary(v => v.Name, v => v.Account), currencyOf, held, now, cancellationToken).ConfigureAwait(false); + await SeedStopsAndChecksAsync(s, ids, alpaca, held, rome, now, cancellationToken).ConfigureAwait(false); + // F.6: the daily series of the total; accounts and strategies are generated to end on their F.2 and F.3 results. var daily = Csv("daily.csv").Skip(1).Select(r => (Day: DateOnly.ParseExact(r[0], "yyyy-MM-dd", _it), Equity: Number(r[1]), Benchmark: Number(r[2]), Drawdown: Number(r[3]))).ToList(); var total = daily[^1].Equity - 10000m; @@ -151,12 +184,12 @@ public static class DemoMode foreach (var (day, equity, benchmark, drawdown) in daily) { var at = day == DateOnly.FromDateTime(Now.DateTime) ? now : new DateTimeOffset(day.ToDateTime(new TimeOnly(22, 0)), rome.GetUtcOffset(day.ToDateTime(new TimeOnly(22, 0)))); - await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, equity, benchmark, drawdown_pct, created_at) VALUES (@id, @at, 'total', @e, @b, @d, @t)", + await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, world, currency, equity, benchmark, drawdown_pct, created_at) VALUES (@id, @at, 'total', 'simulated', 'EUR', @e, @b, @d, @t)", cancellationToken, ("id", ids.Next()), ("at", at), ("e", equity), ("b", benchmark), ("d", drawdown), ("t", now)).ConfigureAwait(false); foreach (var (scope, account, strategy, start, result) in series) { var value = Math.Round(start + (equity - 10000m) * result / total, 2, MidpointRounding.AwayFromZero); - await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, account_id, strategy, equity, created_at) VALUES (@id, @at, @sc, @a, @st, @e, @t)", + await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, world, currency, account_id, strategy, equity, created_at) VALUES (@id, @at, @sc, 'simulated', 'EUR', @a, @st, @e, @t)", cancellationToken, ("id", ids.Next()), ("at", at), ("sc", scope), ("a", account), ("st", strategy), ("e", value), ("t", now)).ConfigureAwait(false); } } @@ -176,6 +209,116 @@ public static class DemoMode }, cancellationToken).ConfigureAwait(false); } + // F.5: the 41 closed trades. Their net results add up to the "guadagni già incassati" of F.2; the commissions of + // each account go on its first trade. Trades without a symbol in the appendix take one of the strategy's. + private static async Task SeedTradesAsync(DbSession s, IdSource ids, Dictionary accountOf, Dictionary currencyOf, + List<(string Symbol, Guid Instrument, Guid Account, string Strategy, decimal Quantity, decimal Average, decimal Stop, DateTimeOffset Opened)> held, + DateTimeOffset now, CancellationToken cancellationToken) + { + var prices = held.ToDictionary(h => h.Symbol, h => h.Average); + var names = new Dictionary(); + foreach (var (symbol, name, price) in new[] + { + ("TSLA", "Tesla", 250m), ("PG", "Procter & Gamble", 160m), ("LINK/EUR", "Chainlink", 15m), ("V", "Visa", 290m), ("ADA/EUR", "Cardano", 0.6m), + ("AMD", "AMD", 160m), ("UNH", "UnitedHealth", 520m), ("KO", "Coca-Cola", 68m), ("MSFT", "Microsoft", 420m), + }) + { + prices[symbol] = price; + names[symbol] = name; + } + + var instruments = held.ToDictionary(h => h.Symbol, h => h.Instrument); + var fallback = new Dictionary + { + ["crypto_trend"] = ["BTC/EUR", "ETH/EUR", "SOL/EUR"], + ["equity_momentum"] = ["AVGO", "NVDA", "LLY", "JPM", "XOM", "COST"], + ["equity_meanrev"] = ["AAPL", "PG", "V", "KO", "MSFT"], + }; + var fees = new Dictionary { [accountOf["crypto_trend"]] = 14.49m, [accountOf["equity_momentum"]] = Math.Round(0.33m * UsdRate, 2) }; + var rows = Csv("trades.csv").Skip(1).ToList(); + + // In dollars each trade is rounded to the cent; the last one of the account takes the rounding, so the total + // converts back to the euro of F.2 exactly. + var left = rows.GroupBy(r => accountOf[r[1]]).ToDictionary(g => g.Key, g => (Count: g.Count(), Total: Math.Round(g.Sum(r => Number(r[2])) * (currencyOf[g.Key] == "EUR" ? 1m : UsdRate), 2, + MidpointRounding.AwayFromZero))); + for (var i = 0; i < rows.Count; i++) + { + var (strategy, eur) = (rows[i][1], Number(rows[i][2])); + var symbol = rows[i].Length > 3 && rows[i][3].Length > 0 ? rows[i][3] : fallback[strategy][i % fallback[strategy].Length]; + var account = accountOf[strategy]; + if (!instruments.TryGetValue(symbol, out var instrument)) + { + var crypto = symbol.Contains('/', StringComparison.Ordinal); + instrument = ids.Next(); + instruments[symbol] = instrument; + await s.ExecuteAsync("INSERT INTO instruments (id, venue, symbol, name, asset_class, quote_currency, created_at) VALUES (@id, @v, @s, @n, @c, @q, @t)", + cancellationToken, ("id", instrument), ("v", crypto ? "okx" : "alpaca"), ("s", symbol), ("n", names[symbol]), ("c", crypto ? "crypto" : "equity"), ("q", crypto ? "EUR" : "USD"), ("t", now)) + .ConfigureAwait(false); + } + + var currency = currencyOf[account]; + var (count, total) = left[account]; + var realized = count == 1 ? total : currency == "EUR" ? eur : Math.Round(eur * UsdRate, 2, MidpointRounding.AwayFromZero); + left[account] = (count - 1, total - realized); + var fee = fees.Remove(account, out var first) ? first : 0m; + var bought = 600m; + var quantity = Math.Round(bought / prices[symbol], 6); + var closed = now.AddDays(-(rows.Count - i)).AddHours(-3); + await s.ExecuteAsync( + "INSERT INTO trades (id, account_id, instrument_id, strategy, status, opened_at, closed_at, bought_quantity, bought_value, sold_quantity, sold_value, fees, realized, exit_reason, created_at, updated_at) " + + "VALUES (@id, @a, @i, @s, 'closed', @o, @c, @q, @b, @q, @sv, @f, @r, @e, @t, @t)", + cancellationToken, ("id", ids.Next()), ("a", account), ("i", instrument), ("s", strategy), ("o", closed.AddDays(-5)), ("c", closed), ("q", quantity), ("b", bought), + ("sv", bought + realized + fee), ("f", fee), ("r", realized), ("e", realized >= 0m ? "signal" : "stop"), ("t", now)).ConfigureAwait(false); + } + } + + // F.7: the protective stops. On OKX one stop for each coin; on Alpaca a permanent stop on the whole shares, while + // the day stops on the fractions wait for the opening (the market is closed at 08:21). Both accounts were checked + // at 08:20 and agree with the ledger; the keys may trade but not withdraw. + private static async Task SeedStopsAndChecksAsync(DbSession s, IdSource ids, Guid alpaca, + List<(string Symbol, Guid Instrument, Guid Account, string Strategy, decimal Quantity, decimal Average, decimal Stop, DateTimeOffset Opened)> held, + TimeZoneInfo rome, DateTimeOffset now, CancellationToken cancellationToken) + { + DateTimeOffset Local(int daysAgo, int hour, int minute) + { + var local = DateOnly.FromDateTime(Now.DateTime).AddDays(-daysAgo).ToDateTime(new TimeOnly(hour, minute)); + return new DateTimeOffset(local, rome.GetUtcOffset(local)).ToUniversalTime(); + } + + var okxSince = new Dictionary + { + ["BTC/EUR"] = (Local(4, 2, 6), Local(0, 2, 6)), + ["ETH/EUR"] = (Local(2, 9, 14), Local(2, 9, 14)), + ["SOL/EUR"] = (Local(6, 11, 40), Local(6, 11, 40)), + }; + var n = 0; + foreach (var h in held) + { + var whole = decimal.Truncate(h.Quantity); + var onAlpaca = h.Account == alpaca; + if (onAlpaca && whole == 0m) + { + continue; + } + + var (created, updated) = onAlpaca ? (h.Opened, h.Opened) : okxSince[h.Symbol]; + await s.ExecuteAsync( + "INSERT INTO orders (id, account_id, instrument_id, strategy, client_order_id, broker_order_id, side, order_type, quantity, stop_price, status, purpose, time_in_force, " + + "filled_quantity, submitted_at, created_at, updated_at) VALUES (@id, @a, @i, @s, @c, @b, 'sell', 'stop', @q, @st, 'submitted', 'stop', 'gtc', 0, @cr, @cr, @up)", + cancellationToken, ("id", ids.Next()), ("a", h.Account), ("i", h.Instrument), ("s", h.Strategy), ("c", $"ANU-DEMO-STOP-{++n:00}"), ("b", $"demo-{n:00}"), + ("q", onAlpaca ? whole : h.Quantity), ("st", h.Stop), ("cr", created), ("up", updated)).ConfigureAwait(false); + } + + var checkedAt = Local(0, 8, 20); + foreach (var account in held.Select(h => h.Account).Distinct()) + { + await s.ExecuteAsync( + "INSERT INTO account_status (id, account_id, mode, last_reconciled_at, last_outcome, key_can_trade, key_can_withdraw, key_checked_at, created_at, updated_at) " + + "VALUES (@id, @a, 'normal', @at, 'clean', @yes, @no, @at, @t, @t)", + cancellationToken, ("id", ids.Next()), ("a", account), ("at", checkedAt), ("yes", true), ("no", false), ("t", now)).ConfigureAwait(false); + } + } + /// Reads the aggregates file of a demo folder. public static JsonDocument? ReadAggregates(DataDirectory data) { diff --git a/src/Anubis/Trading/Capital.cs b/src/Anubis/Trading/Capital.cs index 4f1bf63..fae9253 100644 --- a/src/Anubis/Trading/Capital.cs +++ b/src/Anubis/Trading/Capital.cs @@ -21,6 +21,15 @@ public static class Strategies public static string BrokerOf(string strategy) => Base.FirstOrDefault(b => b.Name == strategy).Broker ?? throw new ArgumentException($"Unknown strategy '{strategy}'.", nameof(strategy)); + /// The name the user reads (appendix F): short in tables, with the market in legends. + public static string Label(string strategy, bool withMarket = false) => strategy switch + { + CryptoTrend => "Trend crypto", + EquityMomentum => withMarket ? "Momentum azioni" : "Momentum", + EquityMeanrev => withMarket ? "Mean reversion azioni" : "Mean reversion", + _ => strategy, + }; + /// The currency a broker's ledger is kept in: euro on OKX Europe, dollars on Alpaca (SPEC 7.1). public static string CurrencyOf(string broker) => broker == Venues.Alpaca ? "USD" : "EUR"; diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index b6d458e..5b7ed13 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -450,6 +450,37 @@ public sealed partial class TradingService : IDisposable } } + /// The secrets of a broker's practice keys, in the order the settings form asks for them. + public static IReadOnlyList<(string Name, string Label)> KeyFields(string broker) => broker == Venues.Alpaca + ? [("ALPACA_API_KEY_DEMO", "Chiave (API key ID)"), ("ALPACA_API_SECRET_DEMO", "Segreto (secret key)")] + : [("OKX_API_KEY_DEMO", "Chiave (API key)"), ("OKX_API_SECRET_DEMO", "Segreto (secret key)"), ("OKX_API_PASSPHRASE_DEMO", "Passphrase")]; + + /// + /// Asks the broker what new practice keys may do, before they are saved: a key that may withdraw is never kept + /// (SPEC 2.2). Throws when the broker refuses the key or does not answer. + /// + public async Task TestKeysAsync(string broker, IReadOnlyList values, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(values); + foreach (var value in values) + { + Redactor.Register(value); + } + + IBrokerAccount account = broker == Venues.Alpaca + ? new AlpacaTrading(_http, _clock, new AlpacaCredentials(values[0], values[1]), new AlpacaTradingOptions { Environment = TradingEnvironments.Demo }, _consent, _sockets) + : new OkxTrading(_http, _clock, new OkxCredentials(values[0], values[1], values[2]), + new OkxTradingOptions { Environment = TradingEnvironments.Demo, QuoteCurrency = "EUR" }, _consent, _sockets); + try + { + return await account.GetKeyPermissionsAsync(cancellationToken).ConfigureAwait(false); + } + finally + { + (account as IDisposable)?.Dispose(); + } + } + private IBrokerAccount? Build(AccountContext account, AlpacaCredentials? alpaca, OkxCredentials? okx) { switch (account.Environment) diff --git a/tests/Anubis.Tests/AccountsScreenTests.cs b/tests/Anubis.Tests/AccountsScreenTests.cs new file mode 100644 index 0000000..1b45644 --- /dev/null +++ b/tests/Anubis.Tests/AccountsScreenTests.cs @@ -0,0 +1,152 @@ +using System.Net; +using Anubis.Db; +using Anubis.Server; + +namespace Anubis.Tests; + +/// The Conti e posizioni screen and the accounts part of Impostazioni (issue #32). +[TestClass] +public sealed class AccountsScreenTests +{ + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheDemoShowsTheFiguresOfTheMockup() + { + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]); + var demoRoot = server.Host.Config.Data.Root; + try + { + var page = await server.TextAsync("/conti"); + + // Mockup 02: totals, the two cards, the stops. The ledger computes them from the seeded rows. + foreach (var figure in new[] + { + "10.412,46", "6.671,13", "3.741,33", "4.231,60", "1.905,10", "2.326,50", "+163,45", "+68,15", "14,49", + "6.180,86", "7.170,41", "1.836,23", "2.130,21", "4.344,63", "5.040,20", "+75,83", "+105,03", "0,33", + "+231,60", "+5,79%", "+180,86", "+3,01%", "22,3%", "37,5%", "4,3%", "35,9%", "59,4%", "40,6%", + }) + { + StringAssert.Contains(page, figure, $"Missing {figure} on the Conti page."); + } + + StringAssert.Contains(page, "Attivo, aggiornato oggi alle 02:06"); + StringAssert.Contains(page, "Attivo dal 7 ottobre"); + StringAssert.Contains(page, "5 stop permanenti"); + StringAssert.Contains(page, "6 stop giornalieri"); + StringAssert.Contains(page, "In coda per l'apertura delle 15:30"); + StringAssert.Contains(page, "Registro interno coerente (controllo delle 08:20)"); + StringAssert.Contains(page, "i prelievi sono disattivati"); + StringAssert.Contains(page, "circa 309"); + Assert.IsLessThan(page.IndexOf("Vendi 0,262", StringComparison.Ordinal), page.IndexOf("Vendi 0,0182", StringComparison.Ordinal), "The largest stop comes first."); + + // The filter keeps one account; the CSV has one row per position, for a spreadsheet. + var okx = await server.TextAsync("/conti?conto=okx"); + Assert.IsFalse(okx.Contains("NVDA", StringComparison.Ordinal)); + using var csv = await server.GetAsync("/api/conti/posizioni.csv"); + Assert.AreEqual(HttpStatusCode.OK, csv.StatusCode); + Assert.AreEqual("text/csv", csv.Content.Headers.ContentType?.MediaType); + var bytes = await csv.Content.ReadAsByteArrayAsync(); + CollectionAssert.AreEqual(new byte[] { 0xEF, 0xBB, 0xBF }, bytes[..3], "Excel reads the accents only with the BOM."); + var lines = System.Text.Encoding.UTF8.GetString(bytes[3..]).Split('\n', StringSplitOptions.RemoveEmptyEntries); + Assert.HasCount(11, lines); + StringAssert.StartsWith(lines[1], "BTC/EUR;Bitcoin;okx;crypto_trend;0.0182;68950;71420;EUR;1299.84;44.95;66180;", lines[1]); + + var settings = await server.TextAsync("/impostazioni"); + StringAssert.Contains(settings, "Conti e chiavi"); + StringAssert.Contains(settings, "Nella modalità dimostrativa chiavi e capitale non si cambiano."); + Assert.IsFalse(settings.Contains("/azioni/capitale/", StringComparison.Ordinal), "No capital form in the demo."); + } + finally + { + TempFolder.Delete(demoRoot); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task KeysAreAskedToTheBrokerBeforeTheyAreKept() + { + var network = new FakeHttp() + .On(u => u.AbsolutePath == "/api/v5/account/config", _ => FakeHttp.Respond(Fixture.Text("okx-trading/account-config.json"))) + .On(u => u.AbsolutePath == "/v2/account", _ => FakeHttp.Respond(Fixture.Text("alpaca-trading/account.json"))) + .On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound)); + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network, trading: true); + await server.SignInFirstTimeAsync(); + var secrets = server.Host.Services!.Secrets; + + // The documentation's OKX key may withdraw: refused, nothing saved. + using (var okx = await server.PostFormAsync("/impostazioni", "/azioni/chiavi/okx", + ("OKX_API_KEY_DEMO", "test-okx-key"), ("OKX_API_SECRET_DEMO", "test-okx-secret"), ("OKX_API_PASSPHRASE_DEMO", "test-okx-pass"))) + { + Assert.AreEqual("/impostazioni?errore=prelievo#conti", ServerHarness.Location(okx)); + } + + Assert.IsFalse((await secrets.StatusAsync("OKX_API_KEY_DEMO")).IsSet); + + // A missing field never reaches the broker. + using (var empty = await server.PostFormAsync("/impostazioni", "/azioni/chiavi/alpaca", ("ALPACA_API_KEY_DEMO", "test-alpaca-key"), ("ALPACA_API_SECRET_DEMO", " "))) + { + Assert.AreEqual("/impostazioni?errore=chiavi-vuote#conti", ServerHarness.Location(empty)); + } + + // Alpaca keys never withdraw and this account may trade: kept, encrypted, never shown again; the engine restarts with them. + using (var alpaca = await server.PostFormAsync("/impostazioni", "/azioni/chiavi/alpaca", ("ALPACA_API_KEY_DEMO", "test-alpaca-key"), ("ALPACA_API_SECRET_DEMO", "test-alpaca-secret"))) + { + Assert.AreEqual("/impostazioni?ok=chiavi#conti", ServerHarness.Location(alpaca)); + } + + await server.WaitForAsync(HostMode.Ready); + secrets = server.Host.Services!.Secrets; + Assert.IsTrue((await secrets.StatusAsync("ALPACA_API_SECRET_DEMO")).IsSet); + var settings = await server.TextAsync("/impostazioni"); + Assert.IsFalse(settings.Contains("test-alpaca-secret", StringComparison.Ordinal), "A saved key is never shown again."); + StringAssert.Contains(settings, "Impostata"); + // The engine starts in the background after "ready": the paper account appears within moments. + var accounts = new List(); + for (var i = 0; i < 100 && accounts.Count == 0; i++) + { + accounts = [.. await server.Host.Services.Db.ReadAsync(s => s.QueryAsync("SELECT name FROM accounts WHERE environment = 'demo'", r => r.Text("name")))]; + if (accounts.Count == 0) + { + await Task.Delay(100); + } + } + + CollectionAssert.AreEqual(new[] { "Alpaca paper" }, accounts.ToArray()); + + // Capital in euro, as people type it; dollars need the ECB rate first. + using (var capital = await server.PostFormAsync("/impostazioni", "/azioni/capitale/okx", ("euro", "1.500,50"))) + { + Assert.AreEqual("/impostazioni?ok=capitale#conti", ServerHarness.Location(capital)); + } + + using (var usd = await server.PostFormAsync("/impostazioni", "/azioni/capitale/alpaca", ("euro", "2000"))) + { + Assert.AreEqual("/impostazioni?errore=cambio#conti", ServerHarness.Location(usd)); + } + + using (var bad = await server.PostFormAsync("/impostazioni", "/azioni/capitale/okx", ("euro", "molto"))) + { + Assert.AreEqual("/impostazioni?errore=importo#conti", ServerHarness.Location(bad)); + } + + var changes = await server.Host.Services.Db.ReadAsync(s => s.QueryAsync("SELECT broker, amount_eur FROM capital_changes", r => (r.Text("broker"), r.Money("amount_eur")))); + CollectionAssert.AreEqual(new[] { ("okx", 1500.50m) }, changes.ToArray()); + StringAssert.Contains(await server.TextAsync("/impostazioni"), "Trend crypto: quota 100%"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow("4000", "4000")] + [DataRow("1.500", "1500")] + [DataRow("1.500,50", "1500.50")] + [DataRow("1500,5", "1500.5")] + [DataRow("1500.50", "1500.50")] + [DataRow(" 2 000 € ", "2000")] + [DataRow("10,999", "10.99")] + [DataRow("-5", null)] + [DataRow("abc", null)] + [DataRow("", null)] + public void AmountsAreReadAsPeopleTypeThem(string text, string? expected) => + Assert.AreEqual(expected is null ? null : decimal.Parse(expected, System.Globalization.CultureInfo.InvariantCulture), Forms.ParseEuro(text)); +} diff --git a/tests/Anubis.Tests/ServerHarness.cs b/tests/Anubis.Tests/ServerHarness.cs index 5b4b595..065a83a 100644 --- a/tests/Anubis.Tests/ServerHarness.cs +++ b/tests/Anubis.Tests/ServerHarness.cs @@ -76,7 +76,7 @@ internal sealed partial class ServerHarness : IAsyncDisposable } public static async Task StartAsync(string platform, IReadOnlyDictionary environment, string? dataDir = null, - string[]? extraArgs = null, bool waitReady = true, HttpMessageHandler? marketHttp = null) + string[]? extraArgs = null, bool waitReady = true, HttpMessageHandler? marketHttp = null, bool trading = false) { var owns = dataDir is null; dataDir ??= TempFolder.Create("server"); @@ -89,6 +89,7 @@ internal sealed partial class ServerHarness : IAsyncDisposable MarketData = marketHttp is not null, MarketHttp = marketHttp, MarketSockets = marketHttp is null ? null : () => new FakeSocket(), + Trading = trading, }); await app.StartAsync().ConfigureAwait(false); var cookies = new CookieContainer(); diff --git a/tools/Anubis.Tasks/Program.cs b/tools/Anubis.Tasks/Program.cs index 38e2ace..2393bb6 100644 --- a/tools/Anubis.Tasks/Program.cs +++ b/tools/Anubis.Tasks/Program.cs @@ -135,7 +135,7 @@ int Screenshots(string[] pages) var folder = Path.Combine(root, "artifacts", "screenshots"); Directory.CreateDirectory(folder); - var targets = pages.Length > 0 ? pages : ["/", "/diario", "/impostazioni"]; + var targets = pages.Length > 0 ? pages : ["/", "/conti", "/diario", "/impostazioni"]; using var shots = Shots.Start(browser); foreach (var page in targets) { diff --git a/tools/Anubis.Tasks/Shots.cs b/tools/Anubis.Tasks/Shots.cs index f119c64..0c7074d 100644 --- a/tools/Anubis.Tasks/Shots.cs +++ b/tools/Anubis.Tasks/Shots.cs @@ -96,6 +96,22 @@ internal sealed class Shots : IDisposable }); Send("Page.navigate", new JsonObject { ["url"] = url }, waitForEvent: "Page.loadEventFired"); Thread.Sleep(500); + + // The whole page, not just the first screen: a page taller than the window grows the window to fit. + var metrics = Send("Page.getLayoutMetrics", new JsonObject()); + var full = (int)Math.Ceiling(metrics["cssContentSize"]?["height"]?.GetValue() ?? height); + if (full > height) + { + Send("Emulation.setDeviceMetricsOverride", new JsonObject + { + ["width"] = width, + ["height"] = full, + ["deviceScaleFactor"] = 2, + ["mobile"] = width < 768, + }); + Thread.Sleep(300); + } + var result = Send("Page.captureScreenshot", new JsonObject { ["format"] = "png" }); File.WriteAllBytes(file, Convert.FromBase64String(result["data"]!.GetValue())); } -- 2.54.1 From 60d5ebbc0571a0a35c9ec596be92eb700312a04f Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 10 Nov 2026 21:24:38 +0100 Subject: [PATCH 5/7] Document Phase 3; fix CSV decimals and Alpaca price steps (refs #33 #31 #32 #27) ADR 0009 records the Phase 3 choices; API-NOTES gains the verified trading facts and what Anubis does with each; ROADMAP and STATE mark the phase done with the live-demo conformance waiting for the user's keys. Two defects found while writing the notes: - The positions CSV used dot decimals; SPEC 13 asks for decimal commas. Trailing zeros are dropped so both engines give the same text. - Alpaca's catalogue has no tick, so limit and stop prices were sent unrounded and would get 422 "sub-penny". OrderRules.TickOf applies Alpaca's rule (2 decimals from 1 $, 4 below) to orders, stops and the simulator's own check. Co-Authored-By: Claude Opus 5.5 --- docs/API-NOTES.md | 34 +++++++- docs/ROADMAP.md | 32 ++++---- docs/STATE.md | 20 +++-- docs/adr/0009-scelte-fase-3.md | 77 +++++++++++++++++++ src/Anubis.Server/AccountsView.cs | 5 +- src/Anubis/Trading/OrderManager.Protection.cs | 2 +- src/Anubis/Trading/OrderRules.cs | 19 ++++- src/Anubis/Trading/PaperBroker.cs | 2 +- tests/Anubis.Tests/AccountsScreenTests.cs | 2 +- tests/Anubis.Tests/TradingRulesTests.cs | 6 ++ 10 files changed, 169 insertions(+), 30 deletions(-) create mode 100644 docs/adr/0009-scelte-fase-3.md diff --git a/docs/API-NOTES.md b/docs/API-NOTES.md index 34f3b34..ae9e02a 100644 --- a/docs/API-NOTES.md +++ b/docs/API-NOTES.md @@ -151,8 +151,11 @@ Ogni fatto non verificabile resta dietro una protezione. I nomi delle impostazio | A2 conto reale italiano | Anubis funziona tutto in paper. L'apertura del conto reale è una voce di `GO-LIVE.md`. | 2, 9 | | A3 crypto su Alpaca | L'adapter Alpaca non espone la crypto. | 2 | | A5 notizie Alpaca nel piano gratuito | Fonte facoltativa (`news.alpaca.enabled`): si spegne da sola se risponde 401/403; restano le fonti della sezione 4.4. | 7 | -| O3b coppie del demo europeo | Elenco fisso di coppie in EUR e USDC, confrontato con `account/instruments` appena ci sono le chiavi demo. | 3 | -| O7 liquidità | Elenco fisso di coppie ammesse e filtro sullo spread prima di ogni ordine. | 3, 5 | +| O3b coppie del demo europeo | Elenco fisso di coppie in EUR e USDC, confrontato con `account/instruments` appena ci sono le chiavi demo (in attesa dell'utente). | 3 | +| O7 liquidità | Elenco fisso di coppie ammesse (Fase 2); il filtro sullo spread prima di ogni ordine arriva con le strategie. | 5 | +| Permessi delle chiavi Alpaca | Alpaca non ha permessi per chiave né un modo di leggerli: Anubis tratta ogni chiave come capace di ordinare e mai di prelevare, e usa solo il conto paper. | 3 | +| Riuso dell'id d'ordine dopo la chiusura | Anubis non lo riusa mai: ogni ordine ha un id nuovo e deterministico (ADR 0001). | 3 | +| Attività `FEE` e dividendi di Alpaca | Il conto paper non li simula: si confrontano con la riconciliazione quando ci saranno le chiavi (ADR 0009). | 3, 6 | | F3b limite del calendario | Una richiesta all'ora, al massimo una ogni 5 minuti anche ai riavvii; la pagina di blocco conta come errore. | 2 | | M3 velocità del classificatore | Misura nella Fase 7; sopra i 50 ms per titolo si segnala all'utente. | 7 | | V2 blocco ETF di Alpaca | Filtro ETF di Anubis attivo di base, indipendente dal broker. | 2 | @@ -188,6 +191,33 @@ Fatti controllati scrivendo gli adapter dei dati, il 10/11/2026. Le risposte reg **Non verificabile senza scambi reali** - Se OKX ometta i minuti senza scambi o li dia a volume zero. Il collector tratta un minuto mancante come buco, lo riscarica una volta e poi lo segna "non recuperabile, forse minuti senza scambi". +## Verifiche della Fase 3 (conti e ordini) + +Fatti controllati sulla documentazione ufficiale il 10/11/2026, scrivendo la parte conti degli adapter. Nessuna chiave, nessun ordine: le risposte d'esempio della documentazione stanno in `tests/Anubis.Tests/Fixtures/alpaca-trading` e `okx-trading`, e la batteria di conformità (`BrokerConformanceTests`) le usa senza rete. + +| Fonte | Fatto | Cosa fa Anubis | +|---|---|---| +| Alpaca | Gli ordini su frazioni di azione accettano solo la validità `day`, stop compresi; con `gtc` la risposta è 422 "fractional orders must be DAY orders". | Stop `gtc` sulle azioni intere; sulla parte frazionaria uno stop `day` rimesso a ogni seduta (ADR 0009, punto 8). | +| Alpaca | `client_order_id` fino a 128 caratteri; un id già usato da un ordine attivo dà 422 con codice 40010001. Non è scritto se si possa riusare dopo la chiusura. | Id deterministici `ANU…`, mai riusati; un 422 di id doppio significa che l'invio precedente è arrivato, e l'ordine si rilegge con `orders:by_client_order_id`. | +| Alpaca | Prezzi limite e stop: 2 decimali da 1 $ in su, 4 sotto; altrimenti 422 42210000 "sub-penny increment". | I prezzi si arrotondano prima dell'invio, verso il lato prudente. | +| Alpaca | Nessuna commissione. Tasse dal listino del 12/10/2026: SEC 0,0000206 sul controvalore delle vendite, FINRA TAF a zero, CAT 0,000003 $ per azione su acquisti e vendite, arrotondate per eccesso al centesimo una volta al giorno. | Il simulatore le arrotonda per eccesso a ogni esecuzione (più prudente). | +| Alpaca | Il conto paper non simula tasse né dividendi; il 10% delle esecuzioni è parziale a caso. | Le attività `FEE` e `DIV` si leggono ma si confrontano con il registro solo con le chiavi. | +| Alpaca | Le chiavi non hanno permessi né un modo per leggerli; l'unico segnale è `transfers_blocked` del conto. | Una chiave Alpaca vale "ordina, non preleva". Anubis la usa solo verso il conto paper. | +| Alpaca | Gli ordini `gtc` si annullano da soli dopo 90 giorni (`expires_at`). | Il gestore rimette lo stop quando lo vede chiuso. | +| Alpaca | Il flusso `trade_updates` ha due eventi in più (`order_replace_rejected`, `order_cancel_rejected`) e lo stato `held`. | Lo stato si prende dall'ordine dentro il messaggio; uno stato sconosciuto conta come "inviato" e le esecuzioni arrivano comunque dalla richiesta REST. | +| OKX | `clOrdId` è unico solo tra gli ordini aperti; il doppione dà 51016 ("Client order ID already exists"), 51065 per gli algoritmici. | 51016 e 51065 vogliono dire "l'invio precedente è arrivato": si rilegge l'ordine invece di rimandarlo. | +| OKX | Un ordine annullato senza esecuzioni sparisce dallo storico dopo 2 ore. | Un ordine OKX sconosciuto al broker da più di 2 ore si considera annullato (ADR 0009). | +| OKX | Le esecuzioni non hanno un `fillId`: la chiave è `tradeId`, unica per strumento. | Ogni esecuzione si registra una volta come `instId:tradeId`. | +| OKX | Un ordine market spot che supera il saldo viene ridotto e eseguito, non rifiutato. | Il registro prende la quantità eseguita davvero, non quella chiesta. | +| OKX | Gli ordini trigger (stop) non bloccano le monete: se allo scatto il saldo è minore, OKX vende quello che c'è. | Gli stop seguono la quantità della posizione dopo ogni esecuzione. | +| OKX | `account/config` dà `perm` con `read_only`, `trade`, `withdraw`, e `feeType` (0 commissione nella moneta ricevuta, 1 nella valuta di quotazione). La chiave d'esempio della documentazione ha `withdraw`. | La chiave d'esempio è rifiutata (test `KeysAreAskedToTheBrokerBeforeTheyAreKept`); una chiave con `withdraw` tiene il conto in modalità prudente. | +| OKX | Il canale `orders` è su `/ws/v5/private` e non manda lo stato iniziale; `orders-algo` è su `/ws/v5/business`. | Il flusso serve solo ad accorgersi prima: ordini ed esecuzioni si rileggono comunque via REST a intervalli regolari, che coprono anche i buchi del flusso. | +| OKX | La pagina delle tariffe e l'esempio di `trade-fee` mostrano ancora 0,08% maker e 0,10% taker; l'avviso per l'Europa dice 0,10% e 0,20% dal 25/09/2026 (O5). | Il simulatore usa la tariffa più alta; con le chiavi vale `trade-fee` del conto. | + +**In attesa delle chiavi dei conti di prova** +- Le classi `AlpacaPaperConformance` e `OkxDemoConformance` (categoria `LiveDemo`) eseguono la stessa batteria sui veri conti di prova. Senza chiavi risultano "in attesa dell'utente". +- Da controllare con le chiavi: l'elenco delle coppie del demo europeo (O3b), se OKX chieda `tradeQuoteCcy` ai conti europei, i caratteri ammessi in `client_order_id` su Alpaca. + ## Versioni di .NET e dei pacchetti ammessi Ultime versioni stabili lette dall'API di NuGet il 10 novembre 2026. Quelle già in uso sono fissate in `Directory.Packages.props`. Gli altri pacchetti si aggiungono nella fase in cui servono, dopo un nuovo controllo della versione. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index e5a9be6..53ac18b 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -10,9 +10,9 @@ aperta la fase. Se questo file e Gitea divergono, vale Gitea e si corregge quest | Fase | Titolo | Stato | |---|---|---| | 0 | [Preparazione](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/27) | Completata | -| 1 | [Fondamenta](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/28) | Da fare | -| 2 | [Dati di mercato](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/29) | Da fare | -| 3 | [Conti, ordini, contabilità](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/30) | Da fare | +| 1 | [Fondamenta](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/28) | Completata | +| 2 | [Dati di mercato](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/29) | Completata (azioni in attesa delle chiavi Alpaca) | +| 3 | [Conti, ordini, contabilità](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/30) | Completata (conti di prova in attesa delle chiavi) | | 4 | [Backtest e laboratorio](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/31) | Da fare | | 5 | [Strategie, portafoglio, rischio](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/32) | Da fare | | 6 | [Motore dal vivo in simulazione](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/milestone/33) | Da fare | @@ -111,22 +111,22 @@ Ordini sicuri e ogni euro tracciato. **Lavori** -- [ ] [#26](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/26) Conti e ordini nell'interfaccia BrokerAdapter e simulatore interno (PaperBroker) -- [ ] [#27](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/27) OMS: macchina a stati, identificativi deterministici, limite che insegue, ritmo degli invii -- [ ] [#28](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/28) Stop di protezione: stop sul broker, stop che seguono la quantità, stop già superato, residui invendibili -- [ ] [#29](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/29) Ambienti, capitale affidato e contabilità: registro, lotti, patrimonio, rendimento corretto -- [ ] [#30](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/30) Riconciliazione con i conti e modalità prudente -- [ ] [#31](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/31) Adapter Alpaca (paper) e OKX (demo) e batteria di conformità `live_demo` -- [ ] [#32](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/32) Schermata Conti e posizioni; conti in Impostazioni e nel primo avvio -- [ ] [#33](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/33) Chiusura della fase, revisione indipendente e tag `fase-3` +- [x] [#26](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/26) Conti e ordini nell'interfaccia BrokerAdapter e simulatore interno (PaperBroker) +- [x] [#27](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/27) OMS: macchina a stati, identificativi deterministici, limite che insegue, ritmo degli invii +- [x] [#28](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/28) Stop di protezione: stop sul broker, stop che seguono la quantità, stop già superato, residui invendibili +- [x] [#29](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/29) Ambienti, capitale affidato e contabilità: registro, lotti, patrimonio, rendimento corretto +- [x] [#30](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/30) Riconciliazione con i conti e modalità prudente +- [x] [#31](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/31) Adapter Alpaca (paper) e OKX (demo) e batteria di conformità `live_demo` +- [x] [#32](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/32) Schermata Conti e posizioni; conti in Impostazioni e nel primo avvio +- [x] [#33](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/33) Chiusura della fase, revisione indipendente e tag `fase-3` **Criteri di accettazione** -- [ ] I test di proprietà contabili passano -- [ ] La batteria di conformità passa sul simulatore e, se le chiavi demo ci sono, sui due conti di prova (altrimenti su risposte d'esempio, criterio in attesa dell'utente) -- [ ] I test con guasti di questa parte passano -- [ ] Un test dimostra che gli adapter rifiutano un ambiente reale senza il consenso della configurazione d'avvio, in Docker e su desktop -- [ ] La schermata Conti e posizioni corrisponde al mockup +- [x] I test di proprietà contabili passano (`RandomFillsNeverBreakTheBooks`: esecuzioni casuali a seme fisso, registro, lotti e liquidità sempre in pari) +- [ ] La batteria di conformità passa sul simulatore e, se le chiavi demo ci sono, sui due conti di prova (altrimenti su risposte d'esempio, criterio in attesa dell'utente) — **simulatore e risposte d'esempio fatti** (`PaperBrokerConformance`, `AlpacaDocConformance`, `OkxDocConformance`); **conti di prova in attesa dell'utente** (`AlpacaPaperConformance`, `OkxDemoConformance`) +- [x] I test con guasti di questa parte passano (risposta persa e mai rimandata, esecuzioni doppie, broker che non risponde, stop scattato senza avviso, differenze non spiegate: `OrderManagerTests`, `ReconcilerTests`) +- [x] Un test dimostra che gli adapter rifiutano un ambiente reale senza il consenso della configurazione d'avvio, in Docker e su desktop (`RealAccountsAreRefusedWithoutTheStartupConsent`, `BrokerAdaptersRefuseARealAccountBeforeAnyRequest`) +- [x] La schermata Conti e posizioni corrisponde al mockup (`TheDemoShowsTheFiguresOfTheMockup` e screenshot a 1440 e 390 px, chiaro e scuro) ## Fase 4 — Backtest e laboratorio diff --git a/docs/STATE.md b/docs/STATE.md index 77fe03e..c9572ed 100644 --- a/docs/STATE.md +++ b/docs/STATE.md @@ -4,7 +4,7 @@ Aggiornato: 2026-11-10 ## Fase corrente -**Fase 2 — Dati di mercato: completata**, con la parte azionaria in attesa delle chiavi del conto di prova Alpaca. La prossima è la Fase 3 (Conti, ordini, contabilità), da iniziare con il via dell'utente. +**Fase 3 — Conti, ordini, contabilità: completata**, con le prove sui conti di prova in attesa delle chiavi demo di OKX e di Alpaca. La prossima è la Fase 4 (Backtest e laboratorio), da iniziare con il via dell'utente. ## Fatto @@ -54,6 +54,14 @@ Aggiornato: 2026-11-10 - Universi azionario e crypto "a una certa data", senza ETF né fondi. - Rapporto di qualità dei dati (`anubis data report`, `/api/data/quality`) e sezione Dati in Impostazioni con lo stato di ogni fonte. - Prova sui dati reali: BTC, ETH e SOL in EUR dal 21/11/2023 (1.085 giorni ciascuna, nessun buco) e BTCUSDT di Binance dal 17/08/2017 (3.363 giorni). +- **Fase 3** (scelte nell'ADR 0009, fatti verificati in `docs/API-NOTES.md`): + - Interfaccia comune dei conti (`IBrokerAccount`), simulatore interno (`PaperBroker`) e parte conti degli adapter Alpaca (paper) e OKX (demo). Nessun conto reale viene creato; gli adapter rifiutano l'ambiente reale prima di qualsiasi richiesta. + - Gestore degli ordini: stati che vanno solo avanti, id deterministici mai rimandati due volte, limite che insegue il prezzo, al massimo sei invii al minuto con le vendite per prime. + - Stop sul broker per ogni posizione: permanenti sulle azioni intere, giornalieri sulle frazioni, sempre allineati alla quantità; stop già superato; residui invendibili. + - Contabilità per strategia in sola aggiunta: esecuzioni, lotti, registro della liquidità, capitale affidato in euro diviso per quote, dividendi e frazionamenti, fotografie del patrimonio ogni 5 minuti, rendimento ponderato nel tempo. + - Riconciliazione ogni 5 minuti con modalità prudente, scelta "allinea" o "escludi", blocco delle chiavi che permettono i prelievi. + - Schermata Conti e posizioni come il mockup, esportazione CSV delle posizioni; in Impostazioni chiavi (verificate col broker prima di salvarle) e capitale affidato; la Panoramica indica il capitale come primo passo. + - Batteria di conformità sul simulatore e sulle risposte d'esempio della documentazione; sui conti di prova parte da sola quando ci sono le chiavi. ## In corso @@ -61,12 +69,14 @@ Nulla. ## Prossimo passo -Fase 3, conti, ordini e contabilità: simulatore interno, gestione degli ordini, stop di protezione, contabilità, riconciliazione. Servono le chiavi demo di OKX Europe e quelle del conto di prova Alpaca (vedi sotto); senza, la batteria di conformità gira su risposte d'esempio. +Fase 4, backtest e laboratorio: motore di prova sullo storico, con gli stessi costi e le stesse regole d'ordine della Fase 3, e il confronto "senza bot". Con le chiavi dei conti di prova si possono chiudere i due criteri in attesa (azioni della Fase 2, conti di prova della Fase 3). ## Da sapere - Le immagini .NET 10 sono su Ubuntu 24.04, non Debian (ADR 0006). -- La modalità dimostrativa mostra solo le parti già costruite: conti, posizioni, strategie e notizie della Panoramica arrivano con le loro fasi. +- La modalità dimostrativa mostra solo le parti già costruite: strategie e notizie della Panoramica arrivano con le loro fasi. Nella demo il motore di trading è spento. +- Le chiavi dei conti di prova si inseriscono da Impostazioni → Conti e chiavi oppure nel file `.env`; quelle nelle variabili d'ambiente valgono di più. Una chiave OKX che permette i prelievi viene rifiutata. +- Il capitale affidato si decide in euro in Impostazioni → Conti e chiavi. Finché non c'è, le strategie osservano soltanto. - `tasks dev` fuori da Docker usa la cartella dei dati vera dell'utente: per prove usa `tasks seed-demo`. - Alpaca non ha più conti senza margine: il divieto di leva lo impone Anubis (API-NOTES A14). - OKX: WebSocket sulla porta 443, la 8443 è chiusa (API-NOTES O3). @@ -80,9 +90,9 @@ Fase 3, conti, ordini e contabilità: simulatore interno, gestione degli ordini, | Cosa | Da quando serve | Senza | |---|---|---| -| Via libera per la Fase 3 | Subito | Non si parte | +| Via libera per la Fase 4 | Subito | Non si parte | | Chiavi del conto paper di Alpaca (`ALPACA_API_KEY_DEMO`, `ALPACA_API_SECRET_DEMO`) | Già dalla Fase 2 (dati azionari) | Parte azionaria spenta; storico azionario dal 2016 in attesa | -| Chiavi demo di OKX Europe | Fase 3 (ordini sui conti di prova) | Batteria di conformità su risposte d'esempio; criteri in attesa | +| Chiavi demo di OKX Europe, senza permesso di prelievo | Fase 3 (ordini sui conti di prova) | Batteria di conformità su risposte d'esempio; criterio della Fase 3 in attesa | | Un token Gitea con permesso `write:package` come segreto `REGISTRY_TOKEN` | Fase 9 (pubblicazione dell'immagine) | Pubblicazione a mano | | Token del bot Telegram e chat autorizzata (facoltativi) | Fase 6 | Test con un finto server | | Chiavi FRED e Finnhub (facoltative, gratuite) | Già dalla Fase 2 | Calendario limitato alla settimana corrente; filtro trimestrali spento | diff --git a/docs/adr/0009-scelte-fase-3.md b/docs/adr/0009-scelte-fase-3.md new file mode 100644 index 0000000..47b8adf --- /dev/null +++ b/docs/adr/0009-scelte-fase-3.md @@ -0,0 +1,77 @@ +# 0009 — Scelte della Fase 3: conti, ordini, contabilità + +Data: 2026-11-10 · Stato: accettata · Precisa la specifica (sezioni 7, 8.6, 9, 13.5, 13.6) e gli ADR 0003, 0007 e 0008, senza aggiungere componenti esterni + +## Contesto + +La Fase 3 collega Anubis ai conti: un'interfaccia comune per i broker, il simulatore interno, il gestore degli ordini con gli stop, la contabilità per strategia, la riconciliazione e la schermata Conti e posizioni. Non ci sono ancora chiavi dei conti di prova, quindi tutto è provato sul simulatore e su risposte d'esempio della documentazione. Alcune scelte non sono scritte nella specifica, o la precisano. Le raccolgo qui. + +## Decisione + +**1. Due interfacce separate per i broker.** `IBrokerAccount` (ordini, posizioni, esecuzioni, permessi della chiave) è distinta da `IMarketDataSource` della Fase 2. Il simulatore interno (`PaperBroker`) e i due adapter (`AlpacaTrading`, `OkxTrading`) la implementano allo stesso modo e passano la stessa batteria di prove. + +**2. Mai conti veri in questa fase.** +- Si creano solo i conti "simulatore" e, con le chiavi di prova, "Alpaca paper" e "OKX demo". Un conto reale non viene mai creato. +- Gli adapter rifiutano l'ambiente reale prima di qualsiasi richiesta se manca il consenso di avvio (SPEC 2.2). Lo controllano i test `LiveSafetyTests`. + +**3. Le strategie partono in osservazione, e dove possono.** +- Le tre strategie di base partono nello stadio "osservazione": non ci sono ancora prove storiche (Fase 4). +- Quando compaiono le chiavi di prova, una strategia passa al conto di prova solo se il suo registro sul simulatore è vuoto. Con una storia resta dov'è, così i risultati non si mescolano. + +**4. Il simulatore ha i soldi che i registri gli danno.** Il simulatore non ha denaro proprio: il suo saldo è almeno la liquidità che i registri delle strategie gli affidano, e cresce quando l'utente aumenta il capitale. + +**5. Commissioni prudenti nel simulatore.** +- OKX: 0,10% maker e 0,20% taker, la tariffa annunciata dal 25/09/2026 (API-NOTES O5), trattenuta nella moneta comprata come fa OKX. La pagina delle tariffe e l'esempio di `trade-fee` mostrano ancora 0,08% e 0,10%: il simulatore usa la più alta. Con le chiavi, la tariffa vera del conto si legge da `trade-fee`. +- Alpaca: nessuna commissione, solo le tasse regolamentari del listino di ottobre 2026 (SEC 0,0000206 sul controvalore delle vendite, CAT 0,000003 $ per azione su acquisti e vendite, TAF a zero), arrotondate per eccesso a ogni esecuzione: più prudente dell'arrotondamento giornaliero del broker. +- Le attività `FEE` di Alpaca non entrano ancora nei registri: si confrontano con la riconciliazione quando ci saranno le chiavi. + +**6. Le esecuzioni si registrano da una sola fonte.** Il flusso degli ordini avvisa che qualcosa è cambiato; le esecuzioni si leggono sempre dalla richiesta REST (`GetFills`) e si salvano una volta sola per conto ed esecuzione. Flusso e richiesta non creano doppioni. + +**7. Ogni ordine ha la sua storia.** Anche la creazione è un evento di `order_events`: si vede quando l'ordine è nato, non solo quando è cambiato. + +**8. Gli stop.** +- Ogni posizione ha uno stop sul broker. Se il prezzo non si conosce, è vecchio o il mercato è chiuso, lo stop si mette comunque: meglio uno stop in più che una posizione scoperta. +- Alpaca: stop permanente (`gtc`) sulle azioni intere; sulle frazioni il broker accetta solo ordini `day`, che il gestore rimette dopo la scadenza. A mercato chiuso restano "in coda per l'apertura" e intanto li sorveglia Anubis. +- Un ordine OKX annullato e sconosciuto al broker da più di 2 ore si considera annullato. + +**9. Contabilità per strategia, in sola aggiunta.** +- `fills`, `lots` e `cash_ledger` non si modificano mai: un errore si corregge con una riga di storno. Un test cerca `UPDATE` e `DELETE` su queste tabelle in tutto il codice. +- Il capitale affidato si decide in euro per broker e si divide tra le strategie secondo le quote. Alpaca lo converte al cambio BCE del giorno e da lì tiene il registro in dollari. +- Ridurre il capitale sotto la liquidità libera di una strategia è rifiutato: il bot non vende per restituire capitale. +- I dividendi vanno a chi aveva il titolo alla chiusura prima della data di stacco, calcolato dalle esecuzioni. Caso limite noto: un frazionamento tra l'acquisto e lo stacco. + +**10. Patrimonio e rendimenti.** +- Ogni 5 minuti una fotografia per strategia, per conto e per mondo (circa 7 righe). +- Mondo simulato e mondo reale non si sommano mai: Panoramica e Conti mostrano un solo mondo, quello reale se esiste un conto reale, altrimenti quello simulato. +- I risultati tolgono i versamenti e i prelievi di capitale; la percentuale è ponderata nel tempo (TWR). +- Le carte dei conti in dollari usano l'ultimo cambio; l'effetto del cambio si mostra a parte. +- Il confronto "senza bot" sui conti reali arriva con la Fase 4. + +**11. Riconciliazione.** +- Ogni 5 minuti registro e conto si confrontano. Sul simulatore si controllano solo la coerenza interna e gli stop. +- Una differenza che si spiega da sola (esecuzione in ritardo, frazionamento, stop da rimettere) si sistema. Una che resta porta il conto in modalità prudente: niente nuovi acquisti, vendite e stop proseguono. +- Dopo 15 minuti l'utente sceglie: **allinea** (il registro prende i numeri del conto, con una riga di rettifica che conta come movimento di capitale, non come risultato) o **escludi** (la differenza resta fuori dal registro e non si segnala più). +- Una chiave che permette i prelievi tiene il conto in modalità prudente finché non viene sostituita: non si allinea né si esclude. + +**12. Chiavi inserite dall'interfaccia.** +- Impostazioni → Conti e chiavi accetta le chiavi dei conti di prova. Prima di salvarle Anubis chiede al broker cosa possono fare. Le rifiuta se permettono i prelievi o se non possono fare ordini. +- Salvate, sono cifrate (SPEC 15.4), non si rimostrano mai e il motore riparte da solo per usarle. +- Le chiavi nelle variabili d'ambiente valgono di più e si cambiano solo lì. +- Finché non c'è capitale affidato, la Panoramica indica questo passo come il primo. + +**13. Batteria di conformità dei broker.** +- Una classe astratta di prove, eseguita sul simulatore, sulle risposte d'esempio della documentazione di Alpaca e OKX e, con le chiavi, sui veri conti di prova (categoria `LiveDemo`). +- Senza chiavi le prove dal vivo risultano "in attesa dell'utente". +- La chiave d'esempio di OKX nella documentazione ha il permesso `withdraw`: la batteria verifica che Anubis lo legga. + +**14. La schermata Conti e posizioni.** +- Il valore di ogni posizione si arrotonda al centesimo nella sua valuta, come lo mostra la tabella, così colonne e totali tornano a vista. +- La modalità dimostrativa carica righe di registro, operazioni chiuse, stop, cambio e stato della riconciliazione: è il registro stesso a calcolare i numeri del mockup. + +**15. Niente operazioni nella modalità dimostrativa.** Il motore di trading è spento nella demo: la demo mostra l'appendice F e non manda nulla. + +## Conseguenze + +- Tutto il percorso dell'ordine è provato senza rete. Le prove con i veri conti di prova aspettano le chiavi dell'utente. +- Dove la specifica lascia spazio, si è scelta la strada più prudente: stop sempre presenti, commissioni piene, nessuna vendita forzata, nessun conto reale. +- I casi limite rimasti (dividendo dopo un frazionamento, attività `FEE` di Alpaca) sono scritti qui e si ricontrollano con le chiavi. diff --git a/src/Anubis.Server/AccountsView.cs b/src/Anubis.Server/AccountsView.cs index 4e8bcc8..15f6f3b 100644 --- a/src/Anubis.Server/AccountsView.cs +++ b/src/Anubis.Server/AccountsView.cs @@ -151,7 +151,7 @@ internal sealed record AccountsView( return new AccountsView(cards, rows.Select(r => r.Row).ToList(), pending, others, alpacaStops, residueRows, slices, fx?.Rate, fx?.Date, fxEffect, market.Open, market.Next); } - /// The positions as CSV for a spreadsheet: semicolons, dot decimals, one row per position. + /// The positions as CSV for an Italian spreadsheet (SPEC 13): semicolons, decimal commas, no thousands separator, one row per position. public string Csv(string? broker) { var text = new StringBuilder("strumento;nome;conto;strategia;quantita;prezzo_medio;prezzo_ora;valuta;valore_eur;risultato_eur;stop;aperta_il\n"); @@ -164,7 +164,8 @@ internal sealed record AccountsView( return text.ToString(); - static string Number(decimal value) => value.ToString(CultureInfo.InvariantCulture); + // Trailing zeros dropped, so both database engines give the same text. + static string Number(decimal value) => (value / 1.000000000000000000000000000000000m).ToString(CultureInfo.InvariantCulture).Replace('.', ','); static string Clean(string value) => value.Replace(';', ',').Replace('\n', ' '); } diff --git a/src/Anubis/Trading/OrderManager.Protection.cs b/src/Anubis/Trading/OrderManager.Protection.cs index 9ad618f..9f50528 100644 --- a/src/Anubis/Trading/OrderManager.Protection.cs +++ b/src/Anubis/Trading/OrderManager.Protection.cs @@ -203,7 +203,7 @@ public sealed partial class OrderManager return; } - var level = OrderRules.StopPrice(position.StopPrice.Value, instrument.Spec.TickSize); + var level = OrderRules.StopPrice(position.StopPrice.Value, OrderRules.TickOf(instrument.Spec, position.StopPrice.Value)); var desired = DesiredStops(instrument, position.Quantity); var current = open.Select(o => (o.Quantity - o.Filled, o.TimeInForce)).OrderBy(x => x.Item1).ToList(); if (open.All(o => o.Stop == level) && current.SequenceEqual(desired.OrderBy(x => x.Quantity))) diff --git a/src/Anubis/Trading/OrderRules.cs b/src/Anubis/Trading/OrderRules.cs index f2c491b..ee7f75f 100644 --- a/src/Anubis/Trading/OrderRules.cs +++ b/src/Anubis/Trading/OrderRules.cs @@ -201,6 +201,21 @@ public static class OrderRules return spec.MinNotional ?? (spec.Venue == Venues.Alpaca ? AlpacaMinimumNotional : 0m); } + /// + /// The price step at a price: the venue's tick, or Alpaca's rule when the catalogue has none (2 decimals from 1 $, + /// 4 below; otherwise 422 "sub-penny increment", API-NOTES Fase 3). + /// + public static decimal? TickOf(InstrumentSpec spec, decimal price) + { + ArgumentNullException.ThrowIfNull(spec); + if (spec.TickSize is > 0m) + { + return spec.TickSize; + } + + return spec.Venue == Venues.Alpaca ? (price >= 1m ? 0.01m : 0.0001m) : null; + } + public static decimal RoundDown(decimal value, decimal step) => step <= 0m ? value : Math.Floor(value / step) * step; public static decimal RoundUp(decimal value, decimal step) => step <= 0m ? value : Math.Ceiling(value / step) * step; @@ -242,8 +257,8 @@ public static class OrderRules return new(rounded, null, null, OrderReasons.BelowMinimumSize); } - var limit = limitPrice is null ? (decimal?)null : LimitPrice(limitPrice.Value, side, spec.TickSize); - var stop = stopPrice is null ? (decimal?)null : StopPrice(stopPrice.Value, spec.TickSize); + var limit = limitPrice is null ? (decimal?)null : LimitPrice(limitPrice.Value, side, TickOf(spec, limitPrice.Value)); + var stop = stopPrice is null ? (decimal?)null : StopPrice(stopPrice.Value, TickOf(spec, stopPrice.Value)); var price = limit ?? stop ?? referencePrice; if (price <= 0m) { diff --git a/src/Anubis/Trading/PaperBroker.cs b/src/Anubis/Trading/PaperBroker.cs index 317e4c1..56e9691 100644 --- a/src/Anubis/Trading/PaperBroker.cs +++ b/src/Anubis/Trading/PaperBroker.cs @@ -682,7 +682,7 @@ public sealed class PaperBroker : IBrokerAccount, IDisposable return "stop_must_be_sell"; } - if (spec.TickSize is > 0m && price is { } p && OrderRules.RoundDown(p, spec.TickSize.Value) != p) + if (price is { } p && OrderRules.TickOf(spec, p) is { } tick && OrderRules.RoundDown(p, tick) != p) { return "price_not_on_tick"; } diff --git a/tests/Anubis.Tests/AccountsScreenTests.cs b/tests/Anubis.Tests/AccountsScreenTests.cs index 1b45644..344b7ec 100644 --- a/tests/Anubis.Tests/AccountsScreenTests.cs +++ b/tests/Anubis.Tests/AccountsScreenTests.cs @@ -49,7 +49,7 @@ public sealed class AccountsScreenTests CollectionAssert.AreEqual(new byte[] { 0xEF, 0xBB, 0xBF }, bytes[..3], "Excel reads the accents only with the BOM."); var lines = System.Text.Encoding.UTF8.GetString(bytes[3..]).Split('\n', StringSplitOptions.RemoveEmptyEntries); Assert.HasCount(11, lines); - StringAssert.StartsWith(lines[1], "BTC/EUR;Bitcoin;okx;crypto_trend;0.0182;68950;71420;EUR;1299.84;44.95;66180;", lines[1]); + StringAssert.StartsWith(lines[1], "BTC/EUR;Bitcoin;okx;crypto_trend;0,0182;68950;71420;EUR;1299,84;44,95;66180;", lines[1]); var settings = await server.TextAsync("/impostazioni"); StringAssert.Contains(settings, "Conti e chiavi"); diff --git a/tests/Anubis.Tests/TradingRulesTests.cs b/tests/Anubis.Tests/TradingRulesTests.cs index cf4e6ea..0b6bab4 100644 --- a/tests/Anubis.Tests/TradingRulesTests.cs +++ b/tests/Anubis.Tests/TradingRulesTests.cs @@ -68,6 +68,12 @@ public sealed class TradingRulesTests 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)); -- 2.54.1 From 1a0912e436940f6255012f8007ed376c94a0f1ab Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 10 Nov 2026 21:47:36 +0100 Subject: [PATCH 6/7] Fix the defects found by the Phase 3 review (refs #33 #26 #27 #28 #29 #30 #31 #32) - Splits multiply only the shares held before the ex-date. Old splits in the table no longer inflate positions bought later; the simulator's book follows the same split once, together with the ledger. - Dividends pay the simulator once on the ex-date holdings, and each payment is marked in the same write, so a failure never pays twice. - Positions are marked to market before every equity photograph; until now equity, drawdown and the Conti screen stayed at the last fill. - A sale with no price keeps its broker stops until it can really leave; a purchase with no price is dropped. - A refused sale is retried with pauses of 1, 2, 4, 8 and 15 minutes instead of every tick, and one failing execution no longer stops the stop alignment of the whole account. - On Alpaca a purchase clears the sell stops of every strategy on the symbol and holds them until it ends. - OKX order lookups treat only 51603 as unknown; any other failure is an error, so a lost order is never sent twice. - The reconcile choice and key removal forms now require the antiforgery token; the choice re-runs the comparison and is only offered after the 15 minutes; stale differences are dropped. - A replaced key that cannot withdraw releases the prudent mode. - Re-entering the same euro capital for Alpaca changes nothing; a new amount converts only the euro difference at today's rate. Co-Authored-By: Claude Opus 5.5 --- docs/adr/0009-scelte-fase-3.md | 20 +++-- .../Components/Pages/Conti.razor | 1 + src/Anubis.Server/Forms.cs | 11 ++- src/Anubis/Trading/Capital.cs | 14 +++- src/Anubis/Trading/Ledger.cs | 77 +++++++++++++++---- src/Anubis/Trading/OkxTrading.cs | 7 +- src/Anubis/Trading/OrderManager.Protection.cs | 36 +++++++-- src/Anubis/Trading/OrderManager.cs | 65 ++++++++++++---- src/Anubis/Trading/PaperBroker.cs | 22 +++--- src/Anubis/Trading/Reconciler.cs | 34 ++++++-- src/Anubis/Trading/TradingService.cs | 74 +++++++++++++----- tests/Anubis.Tests/AccountsScreenTests.cs | 9 +++ tests/Anubis.Tests/LedgerTests.cs | 7 +- tests/Anubis.Tests/OrderManagerTests.cs | 14 +++- tests/Anubis.Tests/ReconcilerTests.cs | 16 +++- tests/Anubis.Tests/TradingRulesTests.cs | 23 ++++++ tests/Anubis.Tests/TradingServiceTests.cs | 17 +++- 17 files changed, 358 insertions(+), 89 deletions(-) diff --git a/docs/adr/0009-scelte-fase-3.md b/docs/adr/0009-scelte-fase-3.md index 47b8adf..a5ade1b 100644 --- a/docs/adr/0009-scelte-fase-3.md +++ b/docs/adr/0009-scelte-fase-3.md @@ -32,16 +32,20 @@ La Fase 3 collega Anubis ai conti: un'interfaccia comune per i broker, il simula **8. Gli stop.** - Ogni posizione ha uno stop sul broker. Se il prezzo non si conosce, è vecchio o il mercato è chiuso, lo stop si mette comunque: meglio uno stop in più che una posizione scoperta. - Alpaca: stop permanente (`gtc`) sulle azioni intere; sulle frazioni il broker accetta solo ordini `day`, che il gestore rimette dopo la scadenza. A mercato chiuso restano "in coda per l'apertura" e intanto li sorveglia Anubis. -- Un ordine OKX annullato e sconosciuto al broker da più di 2 ore si considera annullato. +- Un ordine OKX annullato e sconosciuto al broker da più di 2 ore si considera annullato. Conta come "sconosciuto" solo la risposta 51603 ("l'ordine non esiste"): ogni altro errore si riprova, così un ordine perso non parte due volte. +- Se manca il prezzo, una vendita aspetta con gli stop ancora sul broker: si tolgono solo un attimo prima che parta. Un acquisto senza prezzo si lascia cadere. +- Su Alpaca un acquisto toglie gli stop di tutte le strategie sullo stesso titolo, perché Alpaca rifiuta l'acquisto se c'è un qualsiasi stop di vendita, e li rimette quando l'acquisto finisce. +- Una vendita rifiutata non si abbandona, ma si riprova con pause crescenti: 1, 2, 4, 8 minuti, poi ogni 15. La riconciliazione cerca la causa. **9. Contabilità per strategia, in sola aggiunta.** - `fills`, `lots` e `cash_ledger` non si modificano mai: un errore si corregge con una riga di storno. Un test cerca `UPDATE` e `DELETE` su queste tabelle in tutto il codice. -- Il capitale affidato si decide in euro per broker e si divide tra le strategie secondo le quote. Alpaca lo converte al cambio BCE del giorno e da lì tiene il registro in dollari. +- Il capitale affidato si decide in euro per broker e si divide tra le strategie secondo le quote. Alpaca lo converte al cambio BCE del giorno e da lì tiene il registro in dollari. Quando l'importo cambia, si converte solo la differenza in euro: i dollari già affidati restano quelli, così un movimento del cambio non diventa mai un versamento o un prelievo. Salvare lo stesso importo non cambia nulla. - Ridurre il capitale sotto la liquidità libera di una strategia è rifiutato: il bot non vende per restituire capitale. -- I dividendi vanno a chi aveva il titolo alla chiusura prima della data di stacco, calcolato dalle esecuzioni. Caso limite noto: un frazionamento tra l'acquisto e lo stacco. +- I dividendi vanno a chi aveva il titolo alla chiusura prima della data di stacco, calcolato dalle esecuzioni. Caso limite noto: un frazionamento tra l'acquisto e lo stacco. Ogni pagamento ha il suo segno di "già fatto" nella stessa scrittura, così un errore a metà non paga due volte. +- Un frazionamento moltiplica solo le azioni tenute prima della data di stacco: quelle comprate dopo sono già azioni nuove. Un frazionamento vecchio, di quando la strategia non aveva il titolo, non cambia nulla. Il simulatore applica lo stesso frazionamento al suo libro, una volta, insieme al registro. **10. Patrimonio e rendimenti.** -- Ogni 5 minuti una fotografia per strategia, per conto e per mondo (circa 7 righe). +- Ogni 5 minuti una fotografia per strategia, per conto e per mondo (circa 7 righe). Prima di ogni fotografia le posizioni prendono il prezzo di mercato (il medio di una quotazione recente); senza quotazione resta l'ultimo prezzo noto. - Mondo simulato e mondo reale non si sommano mai: Panoramica e Conti mostrano un solo mondo, quello reale se esiste un conto reale, altrimenti quello simulato. - I risultati tolgono i versamenti e i prelievi di capitale; la percentuale è ponderata nel tempo (TWR). - Le carte dei conti in dollari usano l'ultimo cambio; l'effetto del cambio si mostra a parte. @@ -50,14 +54,14 @@ La Fase 3 collega Anubis ai conti: un'interfaccia comune per i broker, il simula **11. Riconciliazione.** - Ogni 5 minuti registro e conto si confrontano. Sul simulatore si controllano solo la coerenza interna e gli stop. - Una differenza che si spiega da sola (esecuzione in ritardo, frazionamento, stop da rimettere) si sistema. Una che resta porta il conto in modalità prudente: niente nuovi acquisti, vendite e stop proseguono. -- Dopo 15 minuti l'utente sceglie: **allinea** (il registro prende i numeri del conto, con una riga di rettifica che conta come movimento di capitale, non come risultato) o **escludi** (la differenza resta fuori dal registro e non si segnala più). -- Una chiave che permette i prelievi tiene il conto in modalità prudente finché non viene sostituita: non si allinea né si esclude. +- Dopo 15 minuti l'utente sceglie: **allinea** (il registro prende i numeri del conto, con una riga di rettifica che conta come movimento di capitale, non come risultato) o **escludi** (la differenza resta fuori dal registro e non si segnala più). Prima di agire la scelta rifà il confronto: si applica solo alle differenze che esistono in quel momento. Se dopo i 15 minuti la differenza sparisce, il conto aspetta comunque la scelta, ma senza differenze vecchie da copiare. +- Una chiave che permette i prelievi tiene il conto in modalità prudente finché non viene sostituita: non si allinea né si esclude. Sostituita con una chiave senza prelievo, il conto torna normale. **12. Chiavi inserite dall'interfaccia.** - Impostazioni → Conti e chiavi accetta le chiavi dei conti di prova. Prima di salvarle Anubis chiede al broker cosa possono fare. Le rifiuta se permettono i prelievi o se non possono fare ordini. - Salvate, sono cifrate (SPEC 15.4), non si rimostrano mai e il motore riparte da solo per usarle. - Le chiavi nelle variabili d'ambiente valgono di più e si cambiano solo lì. -- Finché non c'è capitale affidato, la Panoramica indica questo passo come il primo. +- Chiavi e capitale non entrano nella procedura del primo avvio, che resta corta (password e database) e deve funzionare anche senza chiavi. Al primo accesso, finché non c'è capitale affidato, la Panoramica indica questo passo come il primo e porta a Impostazioni → Conti e chiavi. **13. Batteria di conformità dei broker.** - Una classe astratta di prove, eseguita sul simulatore, sulle risposte d'esempio della documentazione di Alpaca e OKX e, con le chiavi, sui veri conti di prova (categoria `LiveDemo`). @@ -70,6 +74,8 @@ La Fase 3 collega Anubis ai conti: un'interfaccia comune per i broker, il simula **15. Niente operazioni nella modalità dimostrativa.** Il motore di trading è spento nella demo: la demo mostra l'appendice F e non manda nulla. +**16. Il flusso IEX delle azioni passa alla Fase 6.** L'ADR 0008 lo prevedeva in questa fase, per seguire le posizioni azionarie. Senza le chiavi Alpaca non ci sono né dati azionari né posizioni da seguire. E le posizioni non dipendono dal flusso: lo stop sta sul broker e la riconciliazione controlla ogni 5 minuti. Il flusso (al massimo 30 simboli) arriva con il motore dal vivo della Fase 6, che sceglie quali titoli seguire. + ## Conseguenze - Tutto il percorso dell'ordine è provato senza rete. Le prove con i veri conti di prova aspettano le chiavi dell'utente. diff --git a/src/Anubis.Server/Components/Pages/Conti.razor b/src/Anubis.Server/Components/Pages/Conti.razor index a93ed04..9aa295e 100644 --- a/src/Anubis.Server/Components/Pages/Conti.razor +++ b/src/Anubis.Server/Components/Pages/Conti.razor @@ -355,6 +355,7 @@ else ("escludi", _) => ("Fatto: la differenza resta fuori dal registro e il conto è tornato normale.", true), (_, "motore") => ("Il motore di trading non è attivo: riprova tra poco.", false), (_, "chiave") => ("Una chiave che permette i prelievi non si allinea: va sostituita in Impostazioni.", false), + (_, "presto") => ("La scelta si fa dopo 15 minuti di modalità prudente: prima la differenza può ancora spiegarsi da sola.", false), (_, { }) => ("Non è stato possibile completare la scelta: riprova.", false), _ => (null, false), }; diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs index 52969c2..816fd1e 100644 --- a/src/Anubis.Server/Forms.cs +++ b/src/Anubis.Server/Forms.cs @@ -177,7 +177,8 @@ internal static partial class Forms } /// The user's choice for an account in prudent mode after the 15 minutes (SPEC 7.4): align or leave out. - private static async Task ResolveAccountAsync(Guid id, string choice, AnubisHost host, HttpContext context, CancellationToken ct) + // The form is bound even when unused: binding it is what makes the antiforgery check run on the route. + private static async Task ResolveAccountAsync(Guid id, string choice, IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct) { if (choice is not ("allinea" or "escludi")) { @@ -195,6 +196,12 @@ internal static partial class Forms return Results.Redirect("/conti?errore=chiave"); } + if (!state.WaitsForUser(clock.UtcNow, trading.Reconciler.Grace)) + { + // The choice exists only after the 15 minutes (SPEC 7.4): before, the difference may still explain itself. + return Results.Redirect("/conti?errore=presto"); + } + await trading.Reconciler.ResolveAsync(manager, choice == "allinea" ? Anubis.Trading.ReconcileChoice.Align : Anubis.Trading.ReconcileChoice.Exclude, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false); return Results.Redirect("/conti?ok=" + choice); @@ -263,7 +270,7 @@ internal static partial class Forms return Results.Redirect(back + "?ok=chiavi#conti"); } - private static async Task RemoveKeysAsync(string broker, AnubisHost host, HttpContext context, CancellationToken ct) + private static async Task RemoveKeysAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) { const string back = "/impostazioni"; if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca) || host.IsDemo || host.Services is not { } services) diff --git a/src/Anubis/Trading/Capital.cs b/src/Anubis/Trading/Capital.cs index fae9253..66ba715 100644 --- a/src/Anubis/Trading/Capital.cs +++ b/src/Anubis/Trading/Capital.cs @@ -96,6 +96,13 @@ public sealed class Capital(Database db, IClock clock, Ledger ledger, FxStore fx } var currency = Strategies.CurrencyOf(broker); + var previous = await EntrustedAsync(broker, cancellationToken).ConfigureAwait(false); + if (previous is not null && previous.AmountEur == amountEur) + { + // The same amount again changes nothing, whatever the exchange rate did meanwhile. + return previous; + } + var rate = 1m; if (currency != "EUR") { @@ -105,7 +112,12 @@ public sealed class Capital(Database db, IClock clock, Ledger ledger, FxStore fx ?? throw new CapitalException($"Manca il cambio EUR/{currency}: lo scarico ogni giorno dalla BCE, riprova più tardi."); } - var entrusted = new EntrustedCapital(broker, amountEur, currency, rate, Math.Round(amountEur * rate, 2, MidpointRounding.ToZero), changedBy, clock.UtcNow); + // Only the change in euro is converted at today's rate: the dollars already given stay as they are, so a + // move of the exchange rate is never booked as a deposit or a withdrawal. The rate kept is the overall one. + var amount = Math.Round((previous?.Amount ?? 0m) + ((amountEur - (previous?.AmountEur ?? 0m)) * rate), 2, MidpointRounding.ToZero); + amount = amountEur == 0m ? 0m : Math.Max(amount, 0m); + var overall = amountEur > 0m && currency != "EUR" ? Math.Round(amount / amountEur, 6) : rate; + var entrusted = new EntrustedCapital(broker, amountEur, currency, overall, amount, changedBy, clock.UtcNow); var plan = await PlanAsync(broker, entrusted.Amount, null, cancellationToken).ConfigureAwait(false); await db.WriteAsync(s => s.ExecuteAsync( "INSERT INTO capital_changes (id, broker, amount_eur, currency, fx_rate, amount, changed_by, created_at) VALUES (@id, @b, @e, @c, @r, @a, @by, @now)", cancellationToken, diff --git a/src/Anubis/Trading/Ledger.cs b/src/Anubis/Trading/Ledger.cs index caa22be..ffc58f7 100644 --- a/src/Anubis/Trading/Ledger.cs +++ b/src/Anubis/Trading/Ledger.cs @@ -232,8 +232,27 @@ public sealed class Ledger(Database db, IClock clock) } /// A cash dividend for a strategy, recorded on the ex-date (SPEC 7.5). - public Task RecordDividendAsync(Guid accountId, string strategy, decimal amount, string currency, DateTimeOffset exDate, string note, CancellationToken cancellationToken) => - db.WriteAsync(s => AddCashAsync(s, accountId, strategy, currency, amount, LedgerKinds.Dividend, null, note, exDate, cancellationToken), cancellationToken); + /// + /// A cash dividend for a strategy. With the payment and its mark are one write, and a + /// second call with the same key does nothing. + /// + public Task RecordDividendAsync(Guid accountId, string strategy, decimal amount, string currency, DateTimeOffset exDate, string note, CancellationToken cancellationToken, + string? appliedKey = null) => + db.WriteAsync(async s => + { + if (appliedKey is not null) + { + if (await s.CountAsync("SELECT COUNT(*) FROM applied_actions WHERE account_id = @a AND source_key = @k", ("a", accountId), ("k", appliedKey)).ConfigureAwait(false) > 0) + { + return; + } + + await s.ExecuteAsync("INSERT INTO applied_actions (id, account_id, source_key, created_at) VALUES (@id, @a, @k, @now)", cancellationToken, + ("id", Ids.NewId(clock)), ("a", accountId), ("k", appliedKey), ("now", clock.UtcNow)).ConfigureAwait(false); + } + + await AddCashAsync(s, accountId, strategy, currency, amount, LedgerKinds.Dividend, null, note, exDate, cancellationToken).ConfigureAwait(false); + }, cancellationToken); /// /// Writes a residue off the ledger at market value (SPEC 7.2): a sale at that price that brings no money, whose @@ -286,31 +305,55 @@ public sealed class Ledger(Database db, IClock clock) }, cancellationToken); /// - /// A split in an account's ledger (SPEC 6.10): quantities times the ratio, average prices, stops and open lots - /// divided by it; values and results do not change. False when the action was already applied. + /// A split in an account's ledger (SPEC 6.10). Only what was held before the ex-date is multiplied: shares bought + /// on or after it are already new shares. The cost of each position stays the same, so values and results do not + /// change. Returns how many old shares were held across the strategies (0 when none), or null when the action was + /// already applied. /// - public Task ApplySplitAsync(Guid accountId, Guid instrumentId, string sourceKey, decimal ratio, CancellationToken cancellationToken) + public Task ApplySplitAsync(Guid accountId, Guid instrumentId, string sourceKey, decimal ratio, DateTimeOffset exDate, CancellationToken cancellationToken) { ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(ratio, 0m); - return db.WriteAsync(async s => + return db.WriteAsync(async s => { if (await s.CountAsync("SELECT COUNT(*) FROM applied_actions WHERE account_id = @a AND source_key = @k", ("a", accountId), ("k", sourceKey)).ConfigureAwait(false) > 0) { - return false; + return null; } var now = clock.UtcNow; + var (baseCurrency, _) = await CurrenciesAsync(s, instrumentId).ConfigureAwait(false); var positions = (await s.QueryAsync("SELECT account_id, instrument_id, strategy, quantity, average_price, last_price, stop_price, opened_at FROM positions WHERE account_id = @a AND instrument_id = @i", ReadPosition, ("a", accountId), ("i", instrumentId)).ConfigureAwait(false)).ToList(); - foreach (var p in positions) + var oldShares = 0m; + foreach (var p in positions.Where(p => p.Quantity > 0m)) { + // What the fills since the ex-date added or removed is in new shares already; the rest is old. + var since = await s.QueryAsync("SELECT side, quantity, fee, fee_currency FROM fills WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND executed_at >= @at", + r => (Side: Wire.Side(r.Text("side")), Quantity: r.Money("quantity"), Fee: r.Money("fee"), FeeCurrency: r.Text("fee_currency")), + ("a", accountId), ("i", instrumentId), ("s", p.Strategy), ("at", exDate)).ConfigureAwait(false); + var after = since.Sum(r => + { + var inKind = baseCurrency is not null && r.FeeCurrency == baseCurrency ? r.Fee : 0m; + return r.Side == OrderSide.Buy ? r.Quantity - inKind : -(r.Quantity + inKind); + }); + var old = p.Quantity - after; + if (old <= Dust) + { + continue; + } + + oldShares += old; + var quantity = p.Quantity + (old * (ratio - 1m)); + var unchanged = since.Count == 0; await s.ExecuteAsync("UPDATE positions SET quantity = @q, average_price = @p, last_price = @l, stop_price = @st, updated_at = @now WHERE account_id = @a AND instrument_id = @i AND strategy = @s", - cancellationToken, ("q", p.Quantity * ratio), ("p", DbValues.Money(p.AveragePrice / ratio)), ("l", p.LastPrice / ratio), ("st", p.StopPrice / ratio), ("now", now), + cancellationToken, ("q", quantity), ("p", DbValues.Money(p.Quantity * p.AveragePrice / quantity)), + ("l", unchanged ? p.LastPrice / ratio : p.LastPrice), ("st", unchanged ? p.StopPrice / ratio : p.StopPrice), ("now", now), ("a", accountId), ("i", instrumentId), ("s", p.Strategy)).ConfigureAwait(false); - var lots = await s.QueryAsync("SELECT id, fill_id, quantity, price, closes_id FROM lots WHERE account_id = @a AND instrument_id = @i AND strategy = @s", - r => (Id: r.Id("id"), Fill: r.Id("fill_id"), Quantity: r.Money("quantity"), Price: r.Money("price"), Closes: r.IdOrNull("closes_id")), + var lots = await s.QueryAsync( + "SELECT l.id, l.fill_id, l.quantity, l.price, l.closes_id, f.executed_at FROM lots l JOIN fills f ON f.id = l.fill_id WHERE l.account_id = @a AND l.instrument_id = @i AND l.strategy = @s", + r => (Id: r.Id("id"), Fill: r.Id("fill_id"), Quantity: r.Money("quantity"), Price: r.Money("price"), Closes: r.IdOrNull("closes_id"), At: r.Moment("executed_at")), ("a", accountId), ("i", instrumentId), ("s", p.Strategy)).ConfigureAwait(false); - foreach (var lot in lots.Where(l => l.Closes is null && l.Quantity > 0m)) + foreach (var lot in lots.Where(l => l.Closes is null && l.Quantity > 0m && l.At < exDate)) { var remaining = lot.Quantity + lots.Where(c => c.Closes == lot.Id).Sum(c => c.Quantity); if (remaining <= Dust) @@ -328,16 +371,16 @@ public sealed class Ledger(Database db, IClock clock) if (await OpenTradeAsync(s, accountId, instrumentId, p.Strategy).ConfigureAwait(false) is { } trade) { - var row = await s.FirstOrDefaultAsync("SELECT bought_quantity, sold_quantity FROM trades WHERE id = @id", r => (B: r.Money("bought_quantity"), S: r.Money("sold_quantity")), ("id", trade)) - .ConfigureAwait(false); - await s.ExecuteAsync("UPDATE trades SET bought_quantity = @b, sold_quantity = @s, updated_at = @now WHERE id = @id", cancellationToken, - ("b", row.B * ratio), ("s", row.S * ratio), ("now", now), ("id", trade)).ConfigureAwait(false); + // The old shares count as bought again in new shares: bought minus sold still equals the position. + var row = await s.FirstOrDefaultAsync("SELECT bought_quantity FROM trades WHERE id = @id", r => r.Money("bought_quantity"), ("id", trade)).ConfigureAwait(false); + await s.ExecuteAsync("UPDATE trades SET bought_quantity = @b, updated_at = @now WHERE id = @id", cancellationToken, + ("b", row + (old * (ratio - 1m))), ("now", now), ("id", trade)).ConfigureAwait(false); } } await s.ExecuteAsync("INSERT INTO applied_actions (id, account_id, source_key, created_at) VALUES (@id, @a, @k, @now)", cancellationToken, ("id", Ids.NewId(clock)), ("a", accountId), ("k", sourceKey), ("now", now)).ConfigureAwait(false); - return true; + return oldShares; }, cancellationToken); } diff --git a/src/Anubis/Trading/OkxTrading.cs b/src/Anubis/Trading/OkxTrading.cs index 656bd27..d434674 100644 --- a/src/Anubis/Trading/OkxTrading.cs +++ b/src/Anubis/Trading/OkxTrading.cs @@ -165,8 +165,11 @@ public sealed class OkxTrading : IBrokerAccount var (code, _, data) = Envelope(answer); if (code != "0" || data.Count == 0) { - // 51603 "Order does not exist"; a canceled order without fills also disappears after two hours. - return code is "0" or "51603" or "51000" or "1" ? null : throw _http.Failure(url, answer); + // Only 51603 "Order does not exist" (also as the sCode of a failed call) means unknown; a canceled order + // without fills also disappears after two hours. Any other failure is an error, retried later: a generic + // failure taken for "never arrived" would let a lost order be sent twice. + var sCode = data.Count > 0 ? Text(data[0], "sCode") : null; + return code is "0" or "51603" || sCode == "51603" ? null : throw _http.Failure(url, answer); } return stop ? ReadAlgo(data[0]) : ReadOrder(data[0]); diff --git a/src/Anubis/Trading/OrderManager.Protection.cs b/src/Anubis/Trading/OrderManager.Protection.cs index 9f50528..cd7ef7e 100644 --- a/src/Anubis/Trading/OrderManager.Protection.cs +++ b/src/Anubis/Trading/OrderManager.Protection.cs @@ -140,12 +140,20 @@ public sealed partial class OrderManager return; } - var applied = await _ledger.ApplySplitAsync(_account.AccountId, instrument.Id, split.SourceKey, split.Ratio!.Value, cancellationToken).ConfigureAwait(false); - if (!applied) + var exDate = new DateTimeOffset(split.ExDate.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + var oldShares = await _ledger.ApplySplitAsync(_account.AccountId, instrument.Id, split.SourceKey, split.Ratio!.Value, exDate, cancellationToken).ConfigureAwait(false); + if (oldShares is not > 0m) { + // Already applied, or nothing was held before the ex-date: the shares held are new shares already. return; } + if (_broker is PaperBroker paper) + { + // The simulator is the broker of this account: its book follows the same split, once. + await paper.ApplySplitAsync(instrument.Symbol, split.Ratio.Value, oldShares.Value, exDate, cancellationToken).ConfigureAwait(false); + } + foreach (var position in (await _ledger.PositionsAsync(_account.AccountId, cancellationToken).ConfigureAwait(false)).Where(p => p.InstrumentId == instrument.Id)) { await CancelStopsOfAsync(instrument.Id, position.Strategy, instrument, cancellationToken).ConfigureAwait(false); @@ -173,11 +181,14 @@ public sealed partial class OrderManager private async Task AlignPositionAsync(Guid instrumentId, string strategy, Instrument instrument, CancellationToken cancellationToken) { - var working = await _db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM executions WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND status = @w", - ("a", _account.AccountId), ("i", instrumentId), ("s", strategy), ("w", ExecutionStates.Working)), cancellationToken).ConfigureAwait(false); + // An execution in progress owns the stops of its position until it ends. Where the broker refuses a purchase + // while any sell stop rests on the symbol (Alpaca), a purchase of any strategy holds every stop on it. + var sql = "SELECT COUNT(*) FROM executions WHERE account_id = @a AND instrument_id = @i AND status = @w AND (strategy = @s" + + (_broker.Capabilities.OppositeSideBlocked ? " OR side = @buy)" : ")"); + var working = await _db.ReadAsync(s => s.CountAsync(sql, + ("a", _account.AccountId), ("i", instrumentId), ("s", strategy), ("w", ExecutionStates.Working), ("buy", Wire.Text(OrderSide.Buy))), cancellationToken).ConfigureAwait(false); if (working > 0) { - // An execution in progress owns the stops of its position until it ends. return; } @@ -264,6 +275,21 @@ public sealed partial class OrderManager } } + /// Cancels the open stops of every strategy on an instrument (Alpaca blocks the whole symbol). True when none is left. + private async Task ClearSymbolStopsCoreAsync(Guid instrumentId, Instrument instrument, CancellationToken cancellationToken) + { + var strategies = await _db.ReadAsync(s => s.QueryAsync( + "SELECT DISTINCT strategy FROM orders WHERE account_id = @a AND instrument_id = @i AND purpose = 'stop' AND status IN ('created', 'submitted', 'partially_filled')", + r => r.Text("strategy"), ("a", _account.AccountId), ("i", instrumentId)), cancellationToken).ConfigureAwait(false); + var clear = true; + foreach (var strategy in strategies) + { + clear &= await ClearStopsCoreAsync(instrumentId, strategy, instrument, cancellationToken).ConfigureAwait(false); + } + + return clear; + } + /// Cancels the open stops of a position and confirms it with the broker. True when none is left open. private async Task ClearStopsCoreAsync(Guid instrumentId, string strategy, Instrument instrument, CancellationToken cancellationToken) { diff --git a/src/Anubis/Trading/OrderManager.cs b/src/Anubis/Trading/OrderManager.cs index c9410c8..a72cece 100644 --- a/src/Anubis/Trading/OrderManager.cs +++ b/src/Anubis/Trading/OrderManager.cs @@ -174,12 +174,22 @@ public sealed partial class OrderManager : IDisposable { await RefreshOpenOrdersAsync(cancellationToken).ConfigureAwait(false); await SyncFillsCoreAsync(cancellationToken).ConfigureAwait(false); + // One execution that fails must not leave the others, or the stops of the whole account, behind: the + // first failure is raised again only after the stops are aligned. + Exception? failure = null; var plans = new List<(ExecRow Exec, int Priority)>(); foreach (var exec in await WorkingAsync(cancellationToken).ConfigureAwait(false)) { - if (await AdvanceAsync(exec, cancellationToken).ConfigureAwait(false) is { } priority) + try { - plans.Add((exec, priority)); + if (await AdvanceAsync(exec, cancellationToken).ConfigureAwait(false) is { } priority) + { + plans.Add((exec, priority)); + } + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + failure ??= ex; } } @@ -191,11 +201,22 @@ public sealed partial class OrderManager : IDisposable continue; } - await SendStepAsync(exec, cancellationToken).ConfigureAwait(false); + try + { + await SendStepAsync(exec, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + failure ??= ex; + } } await SyncFillsCoreAsync(cancellationToken).ConfigureAwait(false); await AlignStopsCoreAsync(cancellationToken).ConfigureAwait(false); + if (failure is not null) + { + System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(failure); + } } finally { @@ -354,6 +375,14 @@ public sealed partial class OrderManager : IDisposable } } + // A refused sale is never given up, but it is tried again with growing pauses (1, 2, 4, 8, then 15 minutes): + // a refusal that lasts neither floods the broker nor runs out of order ids. Reconciliation finds the cause. + var refused = orders.AsEnumerable().Reverse().TakeWhile(o => o.Status == OrderStatus.Rejected && o.Reason is not ("okx_51006" or "post_only_would_take")).ToList(); + if (exec.Side == OrderSide.Sell && refused.Count > 0 && _clock.UtcNow - refused[0].CreatedAt < RefusalPause(refused.Count)) + { + return null; + } + var filled = orders.Sum(o => o.Filled); var remaining = exec.Quantity - filled; if (exec.Side == OrderSide.Sell) @@ -380,6 +409,18 @@ public sealed partial class OrderManager : IDisposable return null; } + if (quoteNow is null) + { + if (exec.Side == OrderSide.Buy && exec.Sequence == 0) + { + // No price to buy at: the decision is dropped, not left waiting. + await FinishAsync(exec, ExecutionStates.Canceled, OrderReasons.NoPrice, instrument, cancellationToken).ConfigureAwait(false); + } + + // A sale waits for a price with its stops still on the broker: they are removed only right before it leaves. + return null; + } + if (exec.Side == OrderSide.Sell && exec.Sequence == 0 && !await ClearStopsCoreAsync(exec.InstrumentId, exec.Strategy, instrument, cancellationToken).ConfigureAwait(false)) { // The stops on the quantity to sell must be gone first (SPEC 7.2); they come back if the sale stops. @@ -387,14 +428,9 @@ public sealed partial class OrderManager : IDisposable } if (exec.Side == OrderSide.Buy && exec.Sequence == 0 && _broker.Capabilities.OppositeSideBlocked - && !await ClearStopsCoreAsync(exec.InstrumentId, exec.Strategy, instrument, cancellationToken).ConfigureAwait(false)) - { - // Alpaca refuses a purchase while a sell stop rests on the symbol: cancel, buy, put back. - return null; - } - - if (quoteNow is null) + && !await ClearSymbolStopsCoreAsync(exec.InstrumentId, instrument, cancellationToken).ConfigureAwait(false)) { + // Alpaca refuses a purchase while any sell stop rests on the symbol, of any strategy: cancel, buy, put back. return null; } @@ -752,14 +788,17 @@ public sealed partial class OrderManager : IDisposable private const string OrderSelect = "SELECT id, execution_id, instrument_id, strategy, client_order_id, side, order_type, purpose, quantity, limit_price, stop_price, status, filled_quantity, " + - "average_fill_price, reference_price, step, time_in_force, post_only, created_at FROM orders"; + "average_fill_price, reference_price, step, time_in_force, post_only, created_at, reason FROM orders"; private static OrderRow ReadOrder(DbRow r) => new( r.Id("id"), r.IdOrNull("execution_id"), r.Id("instrument_id"), r.Text("strategy"), r.Text("client_order_id"), Wire.Side(r.Text("side")), Wire.Kind(r.Text("order_type")), r.TextOrNull("purpose") is { } p ? Wire.Purpose(p) : OrderPurpose.Entry, r.Money("quantity"), r.MoneyOrNull("limit_price"), r.MoneyOrNull("stop_price"), Wire.Status(r.Text("status")), r.MoneyOrNull("filled_quantity") ?? 0m, r.MoneyOrNull("average_fill_price"), r.MoneyOrNull("reference_price"), r.IsNull("step") ? null : (int)r.Number("step"), r.TextOrNull("time_in_force") is { } t ? Wire.Tif(t) : TimeInForce.Day, - !r.IsNull("post_only") && r.Bool("post_only"), r.Moment("created_at")); + !r.IsNull("post_only") && r.Bool("post_only"), r.Moment("created_at"), r.TextOrNull("reason")); + + /// The pause before trying a refused sale again: 1, 2, 4, 8, then 15 minutes. + internal static TimeSpan RefusalPause(int refusals) => TimeSpan.FromMinutes(Math.Min(15, 1 << Math.Clamp(refusals - 1, 0, 4))); public void Dispose() => _gate.Dispose(); @@ -768,5 +807,5 @@ public sealed partial class OrderManager : IDisposable private sealed record OrderRow(Guid Id, Guid? ExecutionId, Guid InstrumentId, string Strategy, string ClientOrderId, OrderSide Side, OrderKind Kind, OrderPurpose Purpose, decimal Quantity, decimal? Limit, decimal? Stop, OrderStatus Status, decimal Filled, decimal? AveragePrice, decimal? Reference, int? Step, TimeInForce TimeInForce, - bool PostOnly, DateTimeOffset CreatedAt); + bool PostOnly, DateTimeOffset CreatedAt, string? Reason = null); } diff --git a/src/Anubis/Trading/PaperBroker.cs b/src/Anubis/Trading/PaperBroker.cs index 56e9691..b6230d7 100644 --- a/src/Anubis/Trading/PaperBroker.cs +++ b/src/Anubis/Trading/PaperBroker.cs @@ -223,13 +223,13 @@ public sealed class PaperBroker : IBrokerAccount, IDisposable } /// Credits a cash dividend on the quantity held (SPEC 7.3), from the corporate actions. - public async Task PayDividendAsync(string symbol, decimal perShare, string currency, DateTimeOffset at, CancellationToken cancellationToken) + /// Pays a cash dividend on the shares held before the ex-date, as the broker would. + public async Task PayDividendAsync(string symbol, decimal heldBeforeExDate, decimal perShare, string currency, DateTimeOffset at, CancellationToken cancellationToken) { decimal paid = 0m; await WithBookAsync(book => { - var held = book.Holdings.GetValueOrDefault(symbol)?.Quantity ?? 0m; - paid = DbValues.Money(held * perShare); + paid = DbValues.Money(heldBeforeExDate * perShare); if (paid <= 0m) { return false; @@ -242,18 +242,22 @@ public sealed class PaperBroker : IBrokerAccount, IDisposable return paid; } - /// Applies a split to the simulated holding and to resting orders: quantities times the ratio, prices divided. - public async Task ApplySplitAsync(string symbol, decimal ratio, CancellationToken cancellationToken) + /// + /// Applies a split to the simulated holding and to the orders resting since before the ex-date: the + /// held before the ex-date become ratio times as many, at the same cost. + /// + public async Task ApplySplitAsync(string symbol, decimal ratio, decimal oldShares, DateTimeOffset exDate, CancellationToken cancellationToken) { await WithBookAsync(book => { - if (book.Holdings.TryGetValue(symbol, out var holding)) + if (book.Holdings.TryGetValue(symbol, out var holding) && holding.Quantity > 0m) { - holding.Quantity *= ratio; - holding.AveragePrice = DbValues.Money(holding.AveragePrice / ratio); + var quantity = holding.Quantity + (Math.Min(oldShares, holding.Quantity) * (ratio - 1m)); + holding.AveragePrice = DbValues.Money(holding.Quantity * holding.AveragePrice / quantity); + holding.Quantity = quantity; } - foreach (var order in book.Orders.Where(o => o.Request.Symbol == symbol && IsOpen(o))) + foreach (var order in book.Orders.Where(o => o.Request.Symbol == symbol && IsOpen(o) && o.SubmittedAt < exDate)) { order.Request = order.Request with { diff --git a/src/Anubis/Trading/Reconciler.cs b/src/Anubis/Trading/Reconciler.cs index abf0404..78e8378 100644 --- a/src/Anubis/Trading/Reconciler.cs +++ b/src/Anubis/Trading/Reconciler.cs @@ -151,6 +151,7 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger) } var now = clock.UtcNow; + var previous = await StateAsync(account.AccountId, cancellationToken).ConfigureAwait(false); await db.WriteAsync(async s => { await EnsureStatusAsync(s, account.AccountId, now, cancellationToken).ConfigureAwait(false); @@ -160,9 +161,20 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger) { var difference = new AccountDifference(DifferenceKinds.Key, account.Name, 0m, 1m, $"La chiave del conto {account.Name} permette i prelievi: non la uso per nuovi acquisti."); await s.ExecuteAsync("UPDATE account_status SET mode = @m, mode_since = @now, mode_reason = @r, differences = @d, updated_at = @now WHERE account_id = @a", cancellationToken, - ("m", AccountModes.Prudent), ("now", now), ("r", KeyReason), ("d", Stored([difference], [])), ("a", account.AccountId)).ConfigureAwait(false); - await Diary.NotifyAsync(s, clock, "key_can_withdraw", - $"La chiave del conto {account.Name} permette i prelievi. Non faccio nuovi acquisti su quel conto: sostituiscila con una chiave senza prelievo.", cancellationToken).ConfigureAwait(false); + ("m", AccountModes.Prudent), ("now", now), ("r", KeyReason), ("d", Stored([difference], previous.Excluded)), ("a", account.AccountId)).ConfigureAwait(false); + if (previous.ModeReason != KeyReason) + { + await Diary.NotifyAsync(s, clock, "key_can_withdraw", + $"La chiave del conto {account.Name} permette i prelievi. Non faccio nuovi acquisti su quel conto: sostituiscila con una chiave senza prelievo.", cancellationToken).ConfigureAwait(false); + } + } + else if (previous.ModeReason == KeyReason) + { + // The key was replaced with one that cannot withdraw: the lock it caused ends; the next round compares again. + await s.ExecuteAsync("UPDATE account_status SET mode = @m, mode_since = @now, mode_reason = NULL, differences = @d, updated_at = @now WHERE account_id = @a", cancellationToken, + ("m", AccountModes.Normal), ("now", now), ("d", Stored([], previous.Excluded)), ("a", account.AccountId)).ConfigureAwait(false); + await Diary.WriteAsync(s, clock, DiaryKinds.System, "account_normal", + $"La nuova chiave del conto {account.Name} non permette i prelievi: il conto torna normale.", null, cancellationToken).ConfigureAwait(false); } }, cancellationToken).ConfigureAwait(false); return permissions; @@ -177,12 +189,19 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger) { ArgumentNullException.ThrowIfNull(manager); var account = manager.Account; - var state = await StateAsync(account.AccountId, cancellationToken).ConfigureAwait(false); - if (state.ModeReason == KeyReason) + if ((await StateAsync(account.AccountId, cancellationToken).ConfigureAwait(false)).ModeReason == KeyReason) { throw new InvalidOperationException("A key that may withdraw is replaced, not aligned."); } + // Compared again right now: the choice applies to the differences that exist, never to old ones. + await ReconcileAsync(manager, cancellationToken).ConfigureAwait(false); + var state = await StateAsync(account.AccountId, cancellationToken).ConfigureAwait(false); + if (state.Mode != AccountModes.Prudent || state.ModeReason == KeyReason) + { + return; + } + var excluded = state.Excluded.ToList(); if (choice == ReconcileChoice.Align) { @@ -471,6 +490,11 @@ public sealed class Reconciler(Database db, IClock clock, Ledger ledger) stored = []; diary = $"La differenza sul conto {account.Name} si è spiegata da sola: il conto torna normale."; } + else if (mode == AccountModes.Prudent && reason != KeyReason) + { + // After the 15 minutes the user still decides, but nothing old is kept to be aligned. + stored = []; + } await db.WriteAsync(async s => { diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index 5b7ed13..db316aa 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -238,13 +238,13 @@ public sealed partial class TradingService : IDisposable }, cancellationToken).ConfigureAwait(false); } - await GuardAsync("patrimonio", () => Equity.TakeAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + await GuardAsync("patrimonio", () => PhotographAsync(cancellationToken), cancellationToken).ConfigureAwait(false); } public IReadOnlyList Jobs() => [ new ScheduledJob("riconciliazione", "Riconciliazione dei conti", Schedule.Every(TimeSpan.FromMinutes(5)), ReconcileAllAsync), - new ScheduledJob("patrimonio", "Fotografia del patrimonio", Schedule.Every(TimeSpan.FromMinutes(5)), async ct => await Equity.TakeAsync(ct).ConfigureAwait(false)), + new ScheduledJob("patrimonio", "Fotografia del patrimonio", Schedule.Every(TimeSpan.FromMinutes(5)), PhotographAsync), new ScheduledJob("azioni_societarie", "Dividendi e frazionamenti nei registri", Schedule.Every(TimeSpan.FromHours(1)), CorporateActionsAsync), ]; @@ -273,6 +273,34 @@ public sealed partial class TradingService : IDisposable await Task.WhenAll(streams).ConfigureAwait(false); } + /// The positions valued at the market, then the photograph of the equity (SPEC 7.5). + public async Task PhotographAsync(CancellationToken cancellationToken) + { + await MarkPositionsAsync(cancellationToken).ConfigureAwait(false); + await Equity.TakeAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// Writes the mid of a recent quote as the last price of every position, so equity, drawdown and the Conti screen + /// follow the market and not only the last fill. Without a quote the last known price stays. + /// + public async Task MarkPositionsAsync(CancellationToken cancellationToken) + { + var held = (await Ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false)).Select(p => p.InstrumentId).Distinct().ToList(); + foreach (var id in held) + { + if (await _catalog.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } instrument) + { + continue; + } + + if (await Quotes.GetAsync(instrument.Symbol, cancellationToken).ConfigureAwait(false) is { Bid: > 0m, Ask: > 0m } quote && quote.Ask >= quote.Bid) + { + await Ledger.MarkAsync(id, quote.Mid, cancellationToken).ConfigureAwait(false); + } + } + } + public async Task TickAllAsync(CancellationToken cancellationToken) { foreach (var manager in _managers.Values) @@ -331,11 +359,7 @@ public sealed partial class TradingService : IDisposable var instrument = held[action.Symbol]; if (action.ChangesShares) { - if (manager.Broker is PaperBroker paper && !await AppliedAsync(manager.Account.AccountId, action.SourceKey, cancellationToken).ConfigureAwait(false)) - { - await paper.ApplySplitAsync(action.Symbol, action.Ratio!.Value, cancellationToken).ConfigureAwait(false); - } - + // The ledger and, on the simulator, the broker's book, together and once. await manager.ApplySplitAsync(instrument, action, cancellationToken).ConfigureAwait(false); } else if (action.Kind == CorporateActionKinds.CashDividend && action.CashAmount is > 0m) @@ -356,30 +380,40 @@ public sealed partial class TradingService : IDisposable } var exDate = new DateTimeOffset(action.ExDate.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + var currency = action.Currency ?? account.Currency; var strategies = (await Ledger.PositionsAsync(account.AccountId, cancellationToken).ConfigureAwait(false)) .Where(p => p.InstrumentId == instrument.Id).Select(p => p.Strategy).Distinct(StringComparer.Ordinal).ToList(); + var held = new List<(string Strategy, decimal Quantity)>(); foreach (var strategy in strategies) { var quantity = await Ledger.QuantityAtAsync(account.AccountId, instrument.Id, strategy, exDate, cancellationToken).ConfigureAwait(false); - if (quantity <= 0m) + if (quantity > 0m) { - continue; + held.Add((strategy, quantity)); } - - var amount = Math.Round(quantity * action.CashAmount!.Value, 2, MidpointRounding.ToZero); - if (manager.Broker is PaperBroker paper) - { - await paper.PayDividendAsync(action.Symbol, action.CashAmount!.Value, action.Currency ?? account.Currency, exDate, cancellationToken).ConfigureAwait(false); - } - - await Ledger.RecordDividendAsync(account.AccountId, strategy, amount, action.Currency ?? account.Currency, exDate, - $"Dividendo {action.Symbol} {Format.Quantity(action.CashAmount!.Value)} per azione", cancellationToken).ConfigureAwait(false); } - await _db.WriteAsync(s => s.ExecuteAsync("INSERT INTO applied_actions (id, account_id, source_key, created_at) VALUES (@id, @a, @k, @now) ON CONFLICT (account_id, source_key) DO NOTHING", - cancellationToken, ("id", Ids.NewId(_clock)), ("a", account.AccountId), ("k", key), ("now", _clock.UtcNow)), cancellationToken).ConfigureAwait(false); + // Each payment carries its own mark in the same write, so a failure halfway never pays anyone twice. + if (manager.Broker is PaperBroker paper && held.Count > 0 && await MarkAppliedAsync(account.AccountId, key + ":book", cancellationToken).ConfigureAwait(false)) + { + await paper.PayDividendAsync(action.Symbol, held.Sum(h => h.Quantity), action.CashAmount!.Value, currency, exDate, cancellationToken).ConfigureAwait(false); + } + + foreach (var (strategy, quantity) in held) + { + var amount = Math.Round(quantity * action.CashAmount!.Value, 2, MidpointRounding.ToZero); + await Ledger.RecordDividendAsync(account.AccountId, strategy, amount, currency, exDate, + $"Dividendo {action.Symbol} {Format.Quantity(action.CashAmount!.Value)} per azione", cancellationToken, appliedKey: key + ":" + strategy).ConfigureAwait(false); + } + + await MarkAppliedAsync(account.AccountId, key, cancellationToken).ConfigureAwait(false); } + /// Marks an action as applied to an account; false when it already was. + private Task MarkAppliedAsync(Guid accountId, string key, CancellationToken cancellationToken) => + _db.WriteAsync(async s => await s.ExecuteAsync("INSERT INTO applied_actions (id, account_id, source_key, created_at) VALUES (@id, @a, @k, @now) ON CONFLICT (account_id, source_key) DO NOTHING", + cancellationToken, ("id", Ids.NewId(_clock)), ("a", accountId), ("k", key), ("now", _clock.UtcNow)).ConfigureAwait(false) > 0, cancellationToken); + private Task AppliedAsync(Guid accountId, string sourceKey, CancellationToken cancellationToken) => _db.ReadAsync(async s => await s.CountAsync("SELECT COUNT(*) FROM applied_actions WHERE account_id = @a AND source_key = @k", ("a", accountId), ("k", sourceKey)) .ConfigureAwait(false) > 0, cancellationToken); diff --git a/tests/Anubis.Tests/AccountsScreenTests.cs b/tests/Anubis.Tests/AccountsScreenTests.cs index 344b7ec..9c021b8 100644 --- a/tests/Anubis.Tests/AccountsScreenTests.cs +++ b/tests/Anubis.Tests/AccountsScreenTests.cs @@ -101,6 +101,15 @@ public sealed class AccountsScreenTests var settings = await server.TextAsync("/impostazioni"); Assert.IsFalse(settings.Contains("test-alpaca-secret", StringComparison.Ordinal), "A saved key is never shown again."); StringAssert.Contains(settings, "Impostata"); + + // Every form needs its antiforgery token, also the ones that send no field. + foreach (var path in new[] { "/azioni/chiavi/alpaca/togli", "/azioni/conti/" + Guid.NewGuid() + "/allinea" }) + { + using var forged = await server.Http.PostAsync(new Uri(path, UriKind.Relative), new FormUrlEncodedContent([])); + Assert.AreEqual(HttpStatusCode.BadRequest, forged.StatusCode, path); + } + + Assert.IsTrue((await secrets.StatusAsync("ALPACA_API_SECRET_DEMO")).IsSet, "A forged request removes nothing."); // The engine starts in the background after "ready": the paper account appears within moments. var accounts = new List(); for (var i = 0; i < 100 && accounts.Count == 0; i++) diff --git a/tests/Anubis.Tests/LedgerTests.cs b/tests/Anubis.Tests/LedgerTests.cs index 0106cf5..34ed16d 100644 --- a/tests/Anubis.Tests/LedgerTests.cs +++ b/tests/Anubis.Tests/LedgerTests.cs @@ -125,8 +125,11 @@ public sealed class LedgerTests // A 4-for-1 split: four times the shares at a quarter of the price, the value unchanged; applied once. await rig.Ledger.SetStopAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, 180m, _none).ConfigureAwait(false); var before = (await rig.Ledger.EquitiesAsync(_none).ConfigureAwait(false)).Single(e => e.AccountId == alpaca.AccountId); - Assert.IsTrue(await rig.Ledger.ApplySplitAsync(alpaca.AccountId, aapl.Id, "split-aapl-1", 4m, _none).ConfigureAwait(false)); - Assert.IsFalse(await rig.Ledger.ApplySplitAsync(alpaca.AccountId, aapl.Id, "split-aapl-1", 4m, _none).ConfigureAwait(false), "Never twice."); + // A split whose ex-date came before the purchase changes nothing: those shares were new shares already. + Assert.AreEqual(0m, await rig.Ledger.ApplySplitAsync(alpaca.AccountId, aapl.Id, "split-aapl-old", 2m, TradingRig.Start.AddDays(-30), _none).ConfigureAwait(false)); + Assert.AreEqual(10m, (await rig.Ledger.PositionAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!.Quantity); + Assert.AreEqual(10m, await rig.Ledger.ApplySplitAsync(alpaca.AccountId, aapl.Id, "split-aapl-1", 4m, rig.Clock.UtcNow, _none).ConfigureAwait(false)); + Assert.IsNull(await rig.Ledger.ApplySplitAsync(alpaca.AccountId, aapl.Id, "split-aapl-1", 4m, rig.Clock.UtcNow, _none).ConfigureAwait(false), "Never twice."); var split = (await rig.Ledger.PositionAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!; Assert.AreEqual((40m, 50m, 45m), (split.Quantity, split.AveragePrice, split.StopPrice)); Assert.AreEqual(40m, (await rig.Ledger.OpenLotsAsync(alpaca.AccountId, aapl.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false)).Sum(l => l.Remaining)); diff --git a/tests/Anubis.Tests/OrderManagerTests.cs b/tests/Anubis.Tests/OrderManagerTests.cs index 5045bc8..4844f2a 100644 --- a/tests/Anubis.Tests/OrderManagerTests.cs +++ b/tests/Anubis.Tests/OrderManagerTests.cs @@ -111,9 +111,16 @@ public sealed class OrderManagerTests await s.Rig.TurnsAsync(s.Manager, 2, _minute).ConfigureAwait(false); var held = (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.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); - var (execution, _) = await s.Manager.SubmitAsync(Sell(s, held), _none).ConfigureAwait(false); 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(); @@ -239,11 +246,11 @@ public sealed class OrderManagerTests { var first = !applied; applied = true; - return Task.FromResult(first ? new CorporateAction(instrument.Symbol, CorporateActionKinds.Split, new DateOnly(2026, 11, 10), "test", "split-msft") { Ratio = 4m } : null); + 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: Strategies.EquityMomentum), _none).ConfigureAwait(false); await a.Rig.TurnsAsync(a.Manager, 2, _minute).ConfigureAwait(false); - await a.Paper.ApplySplitAsync("MSFT", 4m, _none).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, Strategies.EquityMomentum, 380m, _none).ConfigureAwait(false); await a.Rig.TurnsAsync(a.Manager, 2, _minute).ConfigureAwait(false); @@ -254,6 +261,7 @@ public sealed class OrderManagerTests 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] diff --git a/tests/Anubis.Tests/ReconcilerTests.cs b/tests/Anubis.Tests/ReconcilerTests.cs index 9ec157b..baeac8b 100644 --- a/tests/Anubis.Tests/ReconcilerTests.cs +++ b/tests/Anubis.Tests/ReconcilerTests.cs @@ -123,6 +123,13 @@ public sealed class ReconcilerTests Assert.IsTrue(state.WaitsForUser(s.Rig.Clock.UtcNow, s.Reconciler.Grace)); Assert.HasCount(2, await s.Rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'account_prudent'", r => r.Id("id")).ConfigureAwait(false)); + // If it clears after the 15 minutes the user still decides, but no old difference is kept: "align" could + // otherwise copy numbers that are no longer true. The choice compares again before it acts. + s.Broker.Missing.Clear(); + Assert.AreEqual(AccountModes.Prudent, (await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false)).Mode); + Assert.IsEmpty((await s.Reconciler.StateAsync(s.Account.AccountId, _none).ConfigureAwait(false)).Differences); + s.Broker.Missing["BTC-EUR"] = 0.004m; + // Align: the ledger takes the account's number with an adjustment, and the account is normal again. await s.Reconciler.ResolveAsync(s.Manager, ReconcileChoice.Align, "test", _none).ConfigureAwait(false); Assert.AreEqual(0.00598m, (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Instrument.Id, Strategies.CryptoTrend, _none).ConfigureAwait(false))!.Quantity); @@ -202,7 +209,14 @@ public sealed class ReconcilerTests s.Rig.Clock.Advance(TimeSpan.FromMinutes(5)); Assert.AreEqual(AccountModes.Prudent, (await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false)).Mode); await Assert.ThrowsExactlyAsync(() => s.Reconciler.ResolveAsync(s.Manager, ReconcileChoice.Align, "test", _none)).ConfigureAwait(false); - Assert.HasCount(1, await s.Rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'key_can_withdraw'", r => r.Id("id")).ConfigureAwait(false)); + await s.Reconciler.CheckKeyAsync(s.Manager, _none).ConfigureAwait(false); + Assert.HasCount(1, await s.Rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'key_can_withdraw'", r => r.Id("id")).ConfigureAwait(false), "Notified once."); + + // Replaced by a key without withdrawals: the lock ends, and purchases are allowed again. + s.Broker.KeyCanWithdraw = false; + await s.Reconciler.CheckKeyAsync(s.Manager, _none).ConfigureAwait(false); + Assert.AreEqual(AccountModes.Normal, (await s.Reconciler.ReconcileAsync(s.Manager, _none).ConfigureAwait(false)).Mode); + Assert.IsNull((await s.Manager.SubmitAsync(Entry(s), _none).ConfigureAwait(false)).Refusal); } [TestMethod] diff --git a/tests/Anubis.Tests/TradingRulesTests.cs b/tests/Anubis.Tests/TradingRulesTests.cs index 0b6bab4..1af0f4d 100644 --- a/tests/Anubis.Tests/TradingRulesTests.cs +++ b/tests/Anubis.Tests/TradingRulesTests.cs @@ -79,6 +79,29 @@ public sealed class TradingRulesTests 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() diff --git a/tests/Anubis.Tests/TradingServiceTests.cs b/tests/Anubis.Tests/TradingServiceTests.cs index 00830df..bd943d8 100644 --- a/tests/Anubis.Tests/TradingServiceTests.cs +++ b/tests/Anubis.Tests/TradingServiceTests.cs @@ -92,6 +92,12 @@ public sealed class TradingServiceTests Assert.AreEqual(2200m, await BookAsync(Venues.Alpaca, "USD").ConfigureAwait(false), "Funded once, not again at every call."); var shares = await rig.QueryAsync("SELECT strategy, capital FROM strategy_state ORDER BY strategy", r => (r.Text("strategy"), r.Money("capital"))).ConfigureAwait(false); CollectionAssert.AreEqual(new[] { (Strategies.CryptoTrend, 1000m), (Strategies.EquityMeanrev, 550m), (Strategies.EquityMomentum, 1650m) }, shares.ToArray()); + + // The dollar falls: saving the same euro again changes nothing, and only a new euro amount is converted at today's rate. + await new FxStore(rig.Db, rig.Clock).UpsertAsync([new FxRate("EUR", "USD", new DateOnly(2026, 11, 10), 1.05m, "ecb")], _none).ConfigureAwait(false); + Assert.AreEqual(2200m, (await service.SetCapitalAsync(Venues.Alpaca, 2000m, "test", _none).ConfigureAwait(false)).Amount); + Assert.AreEqual(3250m, (await service.SetCapitalAsync(Venues.Alpaca, 3000m, "test", _none).ConfigureAwait(false)).Amount); + Assert.HasCount(2, await rig.QueryAsync("SELECT id FROM capital_changes WHERE broker = 'alpaca'", r => r.Id("id")).ConfigureAwait(false)); } [TestMethod] @@ -107,10 +113,11 @@ public sealed class TradingServiceTests await service.Ledger.RecordCapitalAsync(account.AccountId, Strategies.EquityMomentum, 5000m, "USD", "test", _none).ConfigureAwait(false); await service.Ledger.RecordFillAsync(rig.Fill(account, msft, Strategies.EquityMomentum, OrderSide.Buy, 10m, 400m, feeCurrency: "USD"), _none).ConfigureAwait(false); - // Bought on Tuesday; Wednesday is the ex-date of 0,75 USD a share; Thursday a 2-for-1 split. + // Bought on Tuesday; Wednesday is the ex-date of 0,75 USD a share; Thursday a 2-for-1 split. A split of last + // month is still in the table: it came before the purchase and must change nothing. await rig.Db.WriteAsync(async s => { - foreach (var (kind, day, ratio, cash, key) in new[] { ("cash_dividend", "2026-11-11", (decimal?)null, (decimal?)0.75m, "div-msft"), ("split", "2026-11-12", 2m, null, "split-msft") }) + foreach (var (kind, day, ratio, cash, key) in new[] { ("cash_dividend", "2026-11-11", (decimal?)null, (decimal?)0.75m, "div-msft"), ("split", "2026-11-12", 2m, null, "split-msft"), ("split", "2026-10-01", 3m, null, "split-msft-old") }) { await s.ExecuteAsync("INSERT INTO corporate_actions (id, symbol, kind, ex_date, ratio, cash_amount, currency, source, source_key, created_at) " + "VALUES (@id, 'MSFT', @k, @d, @r, @c, 'USD', 'test', @key, @now)", _none, @@ -122,6 +129,7 @@ public sealed class TradingServiceTests await service.CorporateActionsAsync(_none).ConfigureAwait(false); Assert.IsEmpty(await DividendsAsync().ConfigureAwait(false), "Nothing before the ex-date."); + Assert.AreEqual(10m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!.Quantity, "An old split is not applied to new shares."); rig.Clock.Advance(TimeSpan.FromDays(1)); await service.CorporateActionsAsync(_none).ConfigureAwait(false); @@ -137,5 +145,10 @@ public sealed class TradingServiceTests Assert.HasCount(1, await DividendsAsync().ConfigureAwait(false)); Assert.HasCount(1, await rig.QueryAsync("SELECT code FROM journal WHERE code = 'split_applied'", r => r.Text("code")).ConfigureAwait(false)); Assert.IsEmpty(http.Requests); + + // Every photograph values the positions at the market, not at their last fill. + service.Quotes.Put(new Quote("MSFT", 230m, 230.10m, rig.Clock.UtcNow)); + await service.PhotographAsync(_none).ConfigureAwait(false); + Assert.AreEqual(230.05m, (await service.Ledger.PositionAsync(account.AccountId, msft.Id, Strategies.EquityMomentum, _none).ConfigureAwait(false))!.LastPrice); } } -- 2.54.1 From 16be51e17594ceed6b37e8482f1cf3bae24b4714 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 10 Nov 2026 22:09:16 +0100 Subject: [PATCH 7/7] Retry test database creation on any transient PostgreSQL error (refs #33) CI run 188 failed once on the SQLite job: a cross-engine test lost its connection (EndOfStreamException) while creating its PostgreSQL database, right after the service container started. The retry covered only timeouts. It now covers every transient Npgsql error and picks a new database name on each attempt, in case the lost answer had already created the database. Test helper only; no product code changes. Co-Authored-By: Claude Opus 5.5 --- tests/Anubis.Tests/TestSupport.cs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/tests/Anubis.Tests/TestSupport.cs b/tests/Anubis.Tests/TestSupport.cs index 0749eb3..36ee6d7 100644 --- a/tests/Anubis.Tests/TestSupport.cs +++ b/tests/Anubis.Tests/TestSupport.cs @@ -136,9 +136,11 @@ internal sealed class TestDb : IAsyncDisposable return new TestDb(new() { Engine = engine, SqlitePath = Path.Combine(folder, "test.sqlite3") }, folder, null); } - var name = "anubis_t_" + Guid.NewGuid().ToString("N"); + string name; for (var attempt = 1; ; attempt++) { + // A new name each time: a dropped connection may have created the database before the answer was lost. + name = "anubis_t_" + Guid.NewGuid().ToString("N"); try { await using var admin = Anubis.Db.Database.Open(AdminSettings()); @@ -148,10 +150,10 @@ internal sealed class TestDb : IAsyncDisposable await command.ExecuteNonQueryAsync().ConfigureAwait(false); break; } - catch (Npgsql.NpgsqlException ex) when (ex.InnerException is TimeoutException && attempt < 4) + catch (Npgsql.NpgsqlException ex) when (ex.IsTransient && attempt < 4) { - // Many tests create their database at once and a busy CI runner can be slow to accept even within the - // longer test timeout. That is the runner, not the code under test. + // Many tests create their database at once and a busy CI runner can be slow to accept, or drop a + // connection while its PostgreSQL service is still settling. That is the runner, not the code under test. await Task.Delay(TimeSpan.FromSeconds(attempt)).ConfigureAwait(false); } } -- 2.54.1