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); + } +}