diff --git a/CLAUDE.md b/CLAUDE.md index 4ab29db..96210ef 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -19,7 +19,7 @@ Dalla radice del repository: `./tasks.ps1 ` (Windows) o `sh ./tasks.sh - `ci`: come la CI. Esegue `check`, poi i test su PostgreSQL (avvia `docker compose up -d --wait postgres`, porta 55432) e infine l'immagine. Richiede Docker. - `hooks`: attiva `.githooks/pre-commit`, che esegue `check` prima di ogni commit. Si fa una volta per copia del repository. - `seed-demo`: la modalità dimostrativa con i dati dell'appendice F, in una cartella e un database a parte, solo dal computer stesso. -- `screenshots`: fotografa Panoramica, Diario e Impostazioni a 1440 px (chiaro e scuro) e a 390 px in `artifacts/screenshots/`. Usa Edge o Chrome già installati. +- `screenshots`: fotografa Panoramica, Conti, Diario e Impostazioni a 1440 px (chiaro e scuro) e a 390 px in `artifacts/screenshots/`. Usa Edge o Chrome già installati. - `desktop-win` (Fase 10): non ancora disponibile. - `docker compose up --build`: l'applicazione su http://localhost:8787 con PostgreSQL, `/health` risponde `ok`. Primo accesso con `ANUBIS_ADMIN_PASSWORD` del compose. diff --git a/src/Anubis.Server/AccountsView.cs b/src/Anubis.Server/AccountsView.cs new file mode 100644 index 0000000..4e8bcc8 --- /dev/null +++ b/src/Anubis.Server/AccountsView.cs @@ -0,0 +1,278 @@ +using System.Globalization; +using System.Text; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.Trading; + +namespace Anubis.Server; + +/// One account of the Conti screen, in its own currency and in euro. +internal sealed record AccountCard(Guid Id, string Name, string Broker, string Environment, string Currency, decimal Cash, decimal Invested, decimal InvestedEur, int Holdings, + decimal Realized, decimal Unrealized, decimal Fees, decimal Flows, AccountState State, decimal Rate) +{ + /// Cash plus the positions, each valued to the cent as the table shows it, so the figures add up on screen. + public decimal Equity => Cash + Invested; + + public string Kind => Broker == Venues.Alpaca ? "Azioni USA" : "Crypto"; + + public string Short => Broker == Venues.Alpaca ? "Alpaca" : "OKX"; + + public decimal Result => Equity - Flows; + + public decimal Percent => Flows > 0m ? Result / Flows * 100m : 0m; + + /// An amount of this account in euro, at the latest rate. + public decimal Eur(decimal amount) => Currency == "EUR" || Rate <= 0m ? amount : amount / Rate; +} + +internal sealed record PositionRow(Guid AccountId, string Broker, string Symbol, string Name, string Strategy, decimal Quantity, decimal Average, decimal Last, decimal? Stop, + string Currency, DateTimeOffset OpenedAt, decimal ValueEur, decimal ResultEur) +{ + public decimal Percent => Average == 0m ? 0m : (Last / Average - 1m) * 100m; +} + +/// A line of "Ordini in attesa": one order, or the stops of Alpaca grouped by validity. +internal sealed record PendingRow(string Action, string Subject, string Where, string Level, string Status, bool Waiting); + +internal sealed record ResidueRow(string Broker, string Symbol, decimal Quantity, decimal Value, string Currency, DateTimeOffset At); + +internal sealed record StrategySlice(string Label, string Color, decimal Eur); + +/// +/// The Conti e posizioni screen (SPEC 13.6, mockup 02): totals, accounts with key and reconciliation, open positions, +/// pending orders, residues and where the money is by currency. One world only: real accounts when there are any, +/// otherwise the simulated ones, so finto and vero never add up (SPEC 7.1). +/// +internal sealed record AccountsView( + IReadOnlyList Accounts, + IReadOnlyList Positions, + IReadOnlyList Pending, + int PendingOthers, + bool AlpacaStops, + IReadOnlyList Residues, + IReadOnlyList Slices, + decimal? UsdRate, + DateOnly? RateDay, + decimal? FxEffect, + bool MarketOpen, + DateTimeOffset MarketNext) +{ + public bool HasAccounts => Accounts.Count > 0; + + public decimal TotalEur => Accounts.Sum(a => a.Eur(a.Equity)); + + public decimal CashEur => Accounts.Sum(a => a.Eur(a.Cash)); + + public decimal InvestedEur => Accounts.Sum(a => a.InvestedEur); + + public decimal ResultEur => Accounts.Sum(a => a.Eur(a.Result)); + + public decimal OpenResultEur => Positions.Sum(p => p.ResultEur); + + public static async Task LoadAsync(AppServices services, IClock clock, TimeZoneInfo zone, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(services); + var ledger = services.Trading?.Ledger ?? new Ledger(services.Db, clock); + var reconciler = services.Trading?.Reconciler ?? new Reconciler(services.Db, clock, ledger); + var fx = await new FxStore(services.Db, clock).LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false); + var rate = fx?.Rate ?? 0m; + + var (accounts, instruments, trades, orders, residues) = await services.Db.ReadAsync(async s => + { + var a = await s.QueryAsync("SELECT id, name, broker, environment, base_currency FROM accounts ORDER BY broker DESC, created_at", + r => (Id: r.Id("id"), Name: r.Text("name"), Broker: r.Text("broker"), Environment: r.Text("environment"), Currency: r.Text("base_currency"))).ConfigureAwait(false); + var i = await s.QueryAsync("SELECT id, symbol, name, quote_currency FROM instruments", + r => (Id: r.Id("id"), Symbol: r.Text("symbol"), Name: r.TextOrNull("name"), Quote: r.TextOrNull("quote_currency"))).ConfigureAwait(false); + var t = await s.QueryAsync("SELECT account_id, realized, fees FROM trades", r => (Account: r.Id("account_id"), Realized: r.Money("realized"), Fees: r.Money("fees"))) + .ConfigureAwait(false); + var o = await s.QueryAsync( + "SELECT account_id, instrument_id, side, order_type, purpose, quantity, filled_quantity, limit_price, stop_price, time_in_force, step, created_at, updated_at FROM orders " + + "WHERE status IN ('created', 'submitted', 'partially_filled') ORDER BY created_at, id", + r => new OpenOrder(r.Id("account_id"), r.Id("instrument_id"), r.Text("side"), r.Text("order_type"), r.TextOrNull("purpose") ?? "entry", r.Money("quantity"), + r.MoneyOrNull("filled_quantity") ?? 0m, r.MoneyOrNull("limit_price"), r.MoneyOrNull("stop_price"), r.TextOrNull("time_in_force") ?? "day", + r.IsNull("step") ? null : (int)r.Number("step"), r.Moment("created_at"), r.Moment("updated_at"))).ConfigureAwait(false); + var res = await s.QueryAsync("SELECT account_id, instrument_id, quantity, value, currency, created_at FROM residues ORDER BY created_at DESC", + r => (Account: r.Id("account_id"), Instrument: r.Id("instrument_id"), Quantity: r.Money("quantity"), Value: r.Money("value"), Currency: r.Text("currency"), + At: r.Moment("created_at"))).ConfigureAwait(false); + return (a, i.ToDictionary(x => x.Id), t, o, res); + }, cancellationToken).ConfigureAwait(false); + + var world = accounts.Any(a => TradingEnvironments.World(a.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated; + accounts = accounts.Where(a => TradingEnvironments.World(a.Environment) == world).ToList(); + var shown = accounts.Select(a => a.Id).ToHashSet(); + var equities = (await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false)).Where(e => shown.Contains(e.AccountId)).ToList(); + var positions = (await ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false)).Where(p => shown.Contains(p.AccountId)).ToList(); + + var rates = accounts.ToDictionary(a => a.Id, a => a.Currency == "USD" ? rate : 1m); + decimal Eur(Guid account, decimal amount) => rates[account] is var r && r > 0m && r != 1m ? amount / r : amount; + var currencies = accounts.ToDictionary(a => a.Id, a => a.Currency); + var rows = positions + .Select(p => + { + var instrument = instruments.GetValueOrDefault(p.InstrumentId); + var value = Math.Round(p.Value, 2, MidpointRounding.AwayFromZero); + return (Native: value, Row: new PositionRow(p.AccountId, accounts.First(a => a.Id == p.AccountId).Broker, instrument.Symbol ?? "?", instrument.Name ?? "", p.Strategy, + p.Quantity, p.AveragePrice, p.LastPrice ?? p.AveragePrice, p.StopPrice, instrument.Quote ?? currencies[p.AccountId], p.OpenedAt, + Math.Round(Eur(p.AccountId, value), 2, MidpointRounding.AwayFromZero), Math.Round(Eur(p.AccountId, p.Unrealized), 2, MidpointRounding.AwayFromZero))); + }) + .OrderByDescending(r => r.Row.ValueEur) + .ToList(); + + var cards = new List(); + foreach (var a in accounts) + { + var mine = equities.Where(e => e.AccountId == a.Id).ToList(); + var held = positions.Where(p => p.AccountId == a.Id).ToList(); + var valued = rows.Where(r => r.Row.AccountId == a.Id).ToList(); + var state = await reconciler.StateAsync(a.Id, cancellationToken).ConfigureAwait(false); + cards.Add(new AccountCard(a.Id, a.Name, a.Broker, a.Environment, a.Currency, mine.Sum(e => e.Cash), valued.Sum(r => r.Native), valued.Sum(r => r.Row.ValueEur), + held.Select(p => p.InstrumentId).Distinct().Count(), trades.Where(t => t.Account == a.Id).Sum(t => t.Realized), held.Sum(p => p.Unrealized), + trades.Where(t => t.Account == a.Id).Sum(t => t.Fees), mine.Sum(e => e.Flows), state, rates[a.Id])); + } + + var byId = cards.ToDictionary(c => c.Id); + var market = MarketState(services.MarketData?.UsCalendar, clock.UtcNow); + var (pending, others, alpacaStops) = PendingRows(orders.Where(o => shown.Contains(o.Account)).ToList(), byId, instruments.ToDictionary(i => i.Key, i => i.Value.Symbol), + positions, market.Open, market.Next, clock.UtcNow, zone); + + var slices = Strategies.Base.Select(b => new StrategySlice(Strategies.Label(b.Name, withMarket: true), "var(--s-" + b.Name.Replace('_', '-') + ")", + rows.Where(r => r.Row.Strategy == b.Name).Sum(r => r.Row.ValueEur))).ToList(); + decimal? fxEffect = null; + if (cards.Count > 0) + { + fxEffect = await services.Db.ReadAsync(s => s.FirstOrDefaultAsync( + "SELECT fx_effect FROM equity_snapshots WHERE scope = 'total' AND world = @w ORDER BY taken_at DESC LIMIT 1", r => r.MoneyOrNull("fx_effect"), ("w", world)), + cancellationToken).ConfigureAwait(false); + } + + var residueRows = residues.Where(r => shown.Contains(r.Account)) + .Select(r => new ResidueRow(byId[r.Account].Short, instruments.GetValueOrDefault(r.Instrument).Symbol ?? "?", r.Quantity, r.Value, r.Currency, r.At)).ToList(); + return new AccountsView(cards, rows.Select(r => r.Row).ToList(), pending, others, alpacaStops, residueRows, slices, fx?.Rate, fx?.Date, fxEffect, market.Open, market.Next); + } + + /// The positions as CSV for a spreadsheet: semicolons, dot decimals, one row per position. + public string Csv(string? broker) + { + var text = new StringBuilder("strumento;nome;conto;strategia;quantita;prezzo_medio;prezzo_ora;valuta;valore_eur;risultato_eur;stop;aperta_il\n"); + foreach (var p in Positions.Where(p => broker is null || p.Broker == broker)) + { + text.Append(string.Join(';', Clean(p.Symbol), Clean(p.Name), p.Broker, p.Strategy, Number(p.Quantity), Number(p.Average), Number(p.Last), p.Currency, + Number(Math.Round(p.ValueEur, 2)), Number(Math.Round(p.ResultEur, 2)), p.Stop is { } stop ? Number(stop) : "", + p.OpenedAt.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture))).Append('\n'); + } + + return text.ToString(); + + static string Number(decimal value) => value.ToString(CultureInfo.InvariantCulture); + + static string Clean(string value) => value.Replace(';', ',').Replace('\n', ' '); + } + + private sealed record OpenOrder(Guid Account, Guid Instrument, string Side, string Kind, string Purpose, decimal Quantity, decimal Filled, decimal? Limit, decimal? Stop, + string Tif, int? Step, DateTimeOffset CreatedAt, DateTimeOffset UpdatedAt); + + private static (List Rows, int Others, bool AlpacaStops) PendingRows(List orders, Dictionary accounts, Dictionary symbols, + IReadOnlyList positions, bool marketOpen, DateTimeOffset marketNext, DateTimeOffset now, TimeZoneInfo zone) + { + var rows = new List(); + var others = 0; + foreach (var o in orders.Where(o => o.Purpose != "stop")) + { + others++; + var account = accounts[o.Account]; + var verb = o.Side == "buy" ? "Compra" : "Vendi"; + var level = o.Limit is { } limit ? Format.Money(limit, account.Currency) : "a mercato"; + var status = o.Step is { } step && o.Kind == "limit" ? $"Passo {Math.Min(step + 1, 4)} di 4, dalle {Local(o.CreatedAt, zone)}" : "In corso dalle " + Local(o.CreatedAt, zone); + rows.Add(new PendingRow($"{verb} {Format.Quantity(o.Quantity - o.Filled)}", symbols.GetValueOrDefault(o.Instrument) ?? "?", account.Short, level, status, false)); + } + + var stops = orders.Where(o => o.Purpose == "stop").ToList(); + foreach (var o in stops.Where(o => accounts[o.Account].Broker != Venues.Alpaca).OrderByDescending(o => (o.Quantity - o.Filled) * (o.Stop ?? 0m))) + { + var account = accounts[o.Account]; + var local = TimeZoneInfo.ConvertTime(o.UpdatedAt, zone); + var status = local.Date == TimeZoneInfo.ConvertTime(now, zone).Date && o.UpdatedAt > o.CreatedAt + ? "Attivo, aggiornato oggi alle " + local.ToString("HH:mm", CultureInfo.InvariantCulture) + : "Attivo dal " + DayMonth(TimeZoneInfo.ConvertTime(o.CreatedAt, zone)); + rows.Add(new PendingRow("Vendi " + Format.Quantity(o.Quantity - o.Filled), symbols.GetValueOrDefault(o.Instrument) ?? "?", account.Short, + o.Stop is { } stop ? Format.Money(stop, account.Currency, decimals: StopDecimals(stop)) : "", status, false)); + } + + var alpaca = stops.Where(o => accounts[o.Account].Broker == Venues.Alpaca).ToList(); + var alpacaHeld = positions.Where(p => accounts.TryGetValue(p.AccountId, out var a) && a.Broker == Venues.Alpaca && p.StopPrice is not null).ToList(); + var gtc = alpaca.Count(o => o.Tif == "gtc"); + var fractions = alpacaHeld.Count(p => p.Quantity != decimal.Truncate(p.Quantity)); + if (gtc > 0) + { + rows.Add(new PendingRow(gtc == 1 ? "1 stop permanente" : $"{gtc} stop permanenti", "sulle azioni intere", "Alpaca", "vedi tabella sopra", gtc == 1 ? "Attivo" : "Attivi", false)); + } + + if (fractions > 0) + { + var opens = Local(marketNext, zone); + rows.Add(new PendingRow(fractions == 1 ? "1 stop giornaliero" : $"{fractions} stop giornalieri", "sulle frazioni di azione", "Alpaca", "vedi tabella sopra", + marketOpen ? "Attivi fino alla chiusura delle " + opens : "In coda per l'apertura delle " + opens, !marketOpen)); + } + + return (rows, others, gtc > 0 || fractions > 0); + } + + /// Whether the US market is open now, and its next close (open) or next open (closed). + public static (bool Open, DateTimeOffset Next) MarketState(IMarketCalendar? calendar, DateTimeOffset now) + { + var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(now, Zones.NewYork).DateTime); + foreach (var useCalendar in new[] { true, false }) + { + for (var d = -1; d <= 8; d++) + { + var day = today.AddDays(d); + var session = useCalendar ? calendar?.SessionOn(day) : Regular(day); + if (session is null) + { + continue; + } + + if (now >= session.OpenUtc && now < session.CloseUtc) + { + return (true, session.CloseUtc); + } + + if (session.OpenUtc > now) + { + return (false, session.OpenUtc); + } + } + } + + return (false, now); + } + + /// A regular session, 9:30 to 16:00 in New York on weekdays: used only when the broker's calendar is not there yet. + private static MarketSession? Regular(DateOnly day) + { + if (day.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday) + { + return null; + } + + DateTimeOffset At(int hour, int minute) + { + var local = day.ToDateTime(new TimeOnly(hour, minute)); + return new DateTimeOffset(local, Zones.NewYork.GetUtcOffset(local)).ToUniversalTime(); + } + + return new MarketSession(day, At(9, 30), At(16, 0)); + } + + private static string Local(DateTimeOffset moment, TimeZoneInfo zone) => TimeZoneInfo.ConvertTime(moment, zone).ToString("HH:mm", CultureInfo.InvariantCulture); + + /// Stops of a thousand or more without cents when they are round (66.180 €), the others with cents (166,00 $). + public static int StopDecimals(decimal stop) => stop >= 1000m && stop == decimal.Truncate(stop) ? 0 : 2; + + public static string DayMonth(DateTimeOffset local) + { + var text = Format.LongDate(DateOnly.FromDateTime(local.DateTime)); + return text[..text.LastIndexOf(' ')]; + } +} diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs index 24f41f7..cf6e46f 100644 --- a/src/Anubis.Server/AnubisHost.cs +++ b/src/Anubis.Server/AnubisHost.cs @@ -387,6 +387,15 @@ internal sealed partial class AnubisHost( Wake(); } + /// Stops and rebuilds the services, so that new broker keys take effect: a few seconds of "avvio". + internal async Task RestartServicesAsync(CancellationToken cancellationToken) + { + using (await ExclusiveAsync(cancellationToken).ConfigureAwait(false)) + { + await ResetAsync().ConfigureAwait(false); + } + } + /// /// Market data needs the network: off in demo mode (SPEC 13.7), when ANUBIS_MARKET_DATA is off, and /// in tests unless they bring their own fake network. diff --git a/src/Anubis.Server/Assets/app.css b/src/Anubis.Server/Assets/app.css index d040a84..4d3bab2 100644 --- a/src/Anubis.Server/Assets/app.css +++ b/src/Anubis.Server/Assets/app.css @@ -325,6 +325,67 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we .chart-table summary { color: var(--link); cursor: pointer; } .chart-table .table-wrap { max-height: 280px; overflow: auto; margin-top: 8px; } +/* ---- Conti e posizioni ---- */ +.muted { color: var(--text-3); font-weight: 400; } +.attention { color: var(--attention); } +.panel-head { display: flex; align-items: center; justify-content: space-between; gap: 12px 16px; flex-wrap: wrap; margin-bottom: 12px; } +.panel-head h2 { margin: 0; } +.panel-tools { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; } +.totals { padding: 24px 28px; } +.totals-cells { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; } +.total-value { font-size: 30px; line-height: 36px; font-weight: 650; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; } +.cell-note { color: var(--text-3); font-size: 13px; } +.split-bar { display: flex; gap: 3px; height: 12px; margin-top: 24px; } +.split-bar span { border-radius: 3px; min-width: 3px; } +.split-bar.slim { height: 12px; margin: 16px 0 12px; } +.split-legend { list-style: none; display: flex; flex-wrap: wrap; gap: 6px 28px; margin: 12px 0 0; padding: 0; color: var(--text-2); font-size: 13.5px; } +.split-legend li { display: inline-flex; align-items: center; gap: 8px; } +.split-legend strong { color: var(--text); font-weight: 600; } +.swatch { display: inline-block; width: 11px; height: 11px; border-radius: 2px; flex: none; margin-right: 8px; vertical-align: -1px; } +.swatch.round { width: 8px; height: 8px; border-radius: 50%; } +.split-legend .swatch { margin-right: 0; } +.account-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(380px, 1fr)); gap: 20px; } +.account { display: flex; flex-direction: column; padding: 22px 26px; } +.account-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; } +.account-head h2 { display: flex; align-items: center; gap: 10px; } +.tag { padding: 2px 8px; border-radius: 6px; background: var(--surface-2); color: var(--text-2); font-size: 13px; font-weight: 500; line-height: 20px; } +.link-state { display: inline-flex; align-items: center; gap: 8px; color: var(--text-2); font-size: 13.5px; } +.link-state.down .dot { background: var(--loss); } +.account-value { display: flex; align-items: baseline; gap: 14px; flex-wrap: wrap; margin: 14px 0 12px; } +.account-equity { font-size: 32px; line-height: 40px; font-weight: 650; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; } +.account-native, .native { color: var(--text-3); font-size: 13.5px; font-weight: 400; } +.native { margin-left: 0.35em; } +.account-lines { display: grid; grid-template-columns: minmax(0, 1fr) auto; margin: 0; font-variant-numeric: tabular-nums; } +.account-lines dt, .account-lines dd { padding: 9px 0; border-top: 1px solid var(--rule-inner); margin: 0; } +.account-lines dt { color: var(--text-2); } +.account-lines dd { text-align: right; } +.account-lines strong { font-weight: 600; } +.account-facts { list-style: none; margin: 16px 0 0; padding: 12px 16px; border-radius: 10px; background: var(--surface-2); display: flex; flex-direction: column; gap: 6px; font-size: 13.5px; color: var(--text-2); } +.account-facts li { display: flex; align-items: flex-start; gap: 10px; } +.account-facts .icon { margin-top: 2px; color: var(--text-3); } +.account-facts .loss .icon, .account-facts .attention .icon { color: inherit; } +.prudent { margin-top: 16px; } +.prudent > div { display: flex; flex-direction: column; gap: 8px; } +.differences { margin: 0; padding-left: 18px; } +.choices { display: flex; gap: 8px; flex-wrap: wrap; } +.choices form { margin: 0; } +.positions th[scope="row"] { font-weight: 400; text-align: left; white-space: nowrap; } +.positions th[scope="row"] strong { font-weight: 650; } +.table tbody tr:last-child td, .table tbody tr:last-child th { border-bottom: 0; } +.table tfoot th, .table tfoot td { padding: 12px 12px 4px 0; border-top: 2px solid var(--text); text-align: left; } +.table tfoot .num { text-align: right; } +.table th[scope="row"] { padding: 10px 12px 10px 0; border-bottom: 1px solid var(--rule-inner); vertical-align: top; } +.pending th[scope="row"], .positions th[scope="row"] { color: var(--text); } +.pending th[scope="row"] { font-weight: 400; text-align: left; } +.pending th[scope="row"] strong { font-weight: 650; } +.order-state { display: inline-flex; align-items: center; gap: 8px; } +.order-state .icon { color: var(--text-3); } +.aside { margin-top: 16px; padding: 12px 16px; border-radius: 10px; background: var(--surface-2); color: var(--text-2); font-size: 13.5px; } +.currency-lines { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 6px 16px; margin: 0 0 12px; font-variant-numeric: tabular-nums; } +.currency-lines dt { display: flex; align-items: center; color: var(--text-2); } +.currency-lines dd { margin: 0; text-align: right; } +.fx-warning { margin-top: 16px; } + /* ---- Service pages ---- */ .service { min-height: 100vh; display: flex; justify-content: center; padding: 48px 16px; } .service-box { width: 100%; max-width: 720px; display: flex; flex-direction: column; gap: 16px; } @@ -362,6 +423,16 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we .statement { font-size: 18px; line-height: 26px; margin-top: 12px; } .columns { grid-template-columns: 1fr; } .row { grid-template-columns: 1fr; } + .totals { padding: 18px; } + .totals-cells { grid-template-columns: 1fr 1fr; gap: 14px; } + .total-value { font-size: 22px; line-height: 28px; } + .split-legend { gap: 6px 16px; } + .account-grid { grid-template-columns: 1fr; gap: 14px; } + .account { padding: 18px; } + .account-equity { font-size: 28px; line-height: 34px; } + .positions .wide { display: none; } + .account-value .cell-change { display: inline-flex; flex-basis: 100%; } + .panel-tools { width: 100%; justify-content: space-between; } .facts { grid-template-columns: 1fr; gap: 2px; } .facts dd { margin-bottom: 8px; } .bottombar { diff --git a/src/Anubis.Server/Components/Icon.razor b/src/Anubis.Server/Components/Icon.razor index 6217352..1de3da8 100644 --- a/src/Anubis.Server/Components/Icon.razor +++ b/src/Anubis.Server/Components/Icon.razor @@ -35,6 +35,9 @@ case "dots": break; + case "download": + + break; case "collapse": break; diff --git a/src/Anubis.Server/Components/Pages/Conti.razor b/src/Anubis.Server/Components/Pages/Conti.razor index e171572..a93ed04 100644 --- a/src/Anubis.Server/Components/Pages/Conti.razor +++ b/src/Anubis.Server/Components/Pages/Conti.razor @@ -1,5 +1,413 @@ +@inherits LoadedComponent @page "/conti" +@inject AnubisHost Host +@inject ShellData Shell +@inject IClock Clock +@using Anubis.Trading +@using Anubis.Data Conti e posizioni · Anubis -Conti, posizioni e ordini arrivano con la contabilità: lì aggiungerai le chiavi dei conti di prova e vedrai patrimonio, liquidità e commissioni di ciascuno. +@{ + var v = _view; + var c = _currency; +} +@if (!v.HasAccounts) +{ + Il bot crea da solo i due simulatori interni, OKX e Alpaca, al primo avvio del motore di trading. I conti di prova dei broker compaiono quando ne aggiungi le chiavi in Impostazioni. +} +else +{ + @if (_message is { } message) + { +

@message

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

Posizioni aperte

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

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

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

Ordini in attesa

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

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

+ } +
+ +
+

In quale valuta sono i soldi

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

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

+ @if (dollars > 0) + { +

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

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

Residui sotto il minimo vendibile

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

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

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

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

+
+

Conti e chiavi

+

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

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

@b.Title

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

Nella modalità dimostrativa chiavi e capitale non si cambiano.

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

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

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

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

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

Capitale affidato a @b.Short

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

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

+ } + else + { +

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

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

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

+ } + } +
+

Dati

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

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

+}
diff --git a/src/Anubis.Server/Endpoints.cs b/src/Anubis.Server/Endpoints.cs index ae96ff6..7ac0522 100644 --- a/src/Anubis.Server/Endpoints.cs +++ b/src/Anubis.Server/Endpoints.cs @@ -146,6 +146,16 @@ internal static partial class Endpoints return format == "md" ? Results.Text(report.ToMarkdown(), "text/markdown; charset=utf-8") : Results.Json(report, _json); }); + // The open positions of the Conti screen as CSV (SPEC 13.6), all accounts or one broker's. + api.MapGet("/conti/posizioni.csv", async (AnubisHost host, ShellData shell, IClock clock, string? conto, CancellationToken ct) => + { + var view = await AccountsView.LoadAsync(host.Services!, clock, shell.Zone, ct).ConfigureAwait(false); + var broker = conto is Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca ? conto : null; + var day = TimeZoneInfo.ConvertTime(clock.UtcNow, shell.Zone).ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); + return Results.File(System.Text.Encoding.UTF8.GetPreamble().Concat(System.Text.Encoding.UTF8.GetBytes(view.Csv(broker))).ToArray(), + "text/csv; charset=utf-8", $"anubis-posizioni-{day}.csv"); + }); + // The external sources and the live feed: what is on, what is off and why (SPEC 4.4). api.MapGet("/data/sources", async (AnubisHost host, IClock clock, CancellationToken ct) => { diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs index 9f05537..52969c2 100644 --- a/src/Anubis.Server/Forms.cs +++ b/src/Anubis.Server/Forms.cs @@ -30,6 +30,10 @@ internal static partial class Forms signed.MapPost("/impostazioni/{key}", SetSettingAsync); signed.MapPost("/bot/{command}", BotAsync); signed.MapPost("/salvataggio", BackupAsync); + signed.MapPost("/conti/{id:guid}/{choice}", ResolveAccountAsync); + signed.MapPost("/chiavi/{broker}", SaveKeysAsync); + signed.MapPost("/chiavi/{broker}/togli", RemoveKeysAsync); + signed.MapPost("/capitale/{broker}", SetCapitalAsync); } private static string Back(IFormCollection form, string fallback) @@ -172,6 +176,165 @@ internal static partial class Forms return Results.Redirect(ok ? back : With(back, "errore", "bot")); } + /// The user's choice for an account in prudent mode after the 15 minutes (SPEC 7.4): align or leave out. + private static async Task ResolveAccountAsync(Guid id, string choice, AnubisHost host, HttpContext context, CancellationToken ct) + { + if (choice is not ("allinea" or "escludi")) + { + return Results.Redirect("/conti?errore=scelta"); + } + + if (host.IsDemo || host.Services?.Trading is not { } trading || trading.ManagerOf(id) is not { } manager) + { + return Results.Redirect("/conti?errore=motore"); + } + + var state = await trading.Reconciler.StateAsync(id, ct).ConfigureAwait(false); + if (state.ModeReason == Anubis.Trading.Reconciler.KeyReason) + { + return Results.Redirect("/conti?errore=chiave"); + } + + await trading.Reconciler.ResolveAsync(manager, choice == "allinea" ? Anubis.Trading.ReconcileChoice.Align : Anubis.Trading.ReconcileChoice.Exclude, + context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false); + return Results.Redirect("/conti?ok=" + choice); + } + + /// + /// New practice keys for a broker (SPEC 13.5): asked to the broker first, kept only if they may trade and may not + /// withdraw (SPEC 2.2), saved encrypted, never shown again. The engine then restarts to use them. + /// + private static async Task SaveKeysAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) + { + const string back = "/impostazioni"; + if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca)) + { + return Results.Redirect(back + "?errore=conto#conti"); + } + + if (host.IsDemo || host.Services is not { Trading: { } trading } services) + { + return Results.Redirect(back + "?errore=motore#conti"); + } + + var fields = Anubis.Trading.TradingService.KeyFields(broker); + foreach (var (name, _) in fields) + { + if ((await services.Secrets.StatusAsync(name, ct).ConfigureAwait(false)).FromEnvironment) + { + return Results.Redirect(back + "?errore=ambiente#conti"); + } + } + + var values = fields.Select(f => form[f.Name].ToString().Trim()).ToList(); + if (values.Any(v => v.Length == 0 || v.Length > 512)) + { + return Results.Redirect(back + "?errore=chiavi-vuote#conti"); + } + + Anubis.Trading.KeyPermissions permissions; + try + { + permissions = await trading.TestKeysAsync(broker, values, ct).ConfigureAwait(false); + } + catch (Anubis.Trading.BrokerException) + { + return Results.Redirect(back + "?errore=chiavi-rifiutate#conti"); + } + + if (permissions.CanWithdraw) + { + return Results.Redirect(back + "?errore=prelievo#conti"); + } + + if (!permissions.CanTrade) + { + return Results.Redirect(back + "?errore=sola-lettura#conti"); + } + + var who = context.User.Identity?.Name ?? "utente"; + for (var i = 0; i < fields.Count; i++) + { + await services.Secrets.SetAsync(fields[i].Name, values[i], who, ct).ConfigureAwait(false); + } + + await host.RestartServicesAsync(ct).ConfigureAwait(false); + await WaitBrieflyAsync(host).ConfigureAwait(false); + return Results.Redirect(back + "?ok=chiavi#conti"); + } + + private static async Task RemoveKeysAsync(string broker, AnubisHost host, HttpContext context, CancellationToken ct) + { + const string back = "/impostazioni"; + if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca) || host.IsDemo || host.Services is not { } services) + { + return Results.Redirect(back + "?errore=conto#conti"); + } + + var who = context.User.Identity?.Name ?? "utente"; + foreach (var (name, _) in Anubis.Trading.TradingService.KeyFields(broker)) + { + await services.Secrets.RemoveAsync(name, who, ct).ConfigureAwait(false); + } + + await host.RestartServicesAsync(ct).ConfigureAwait(false); + await WaitBrieflyAsync(host).ConfigureAwait(false); + return Results.Redirect(back + "?ok=chiavi-tolte#conti"); + } + + /// The capital entrusted to a broker, in euro (SPEC 7.1, 8.6): only the user sets it. + private static async Task SetCapitalAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) + { + const string back = "/impostazioni"; + if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca)) + { + return Results.Redirect(back + "?errore=conto#conti"); + } + + if (host.IsDemo || host.Services?.Trading is not { } trading) + { + return Results.Redirect(back + "?errore=motore#conti"); + } + + if (ParseEuro(form["euro"].ToString()) is not { } amount || amount < 0m || amount > 100_000_000m) + { + return Results.Redirect(back + "?errore=importo#conti"); + } + + try + { + await trading.SetCapitalAsync(broker, amount, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false); + } + catch (Anubis.Trading.CapitalException ex) when (ex.Message.StartsWith("Manca il cambio", StringComparison.Ordinal)) + { + return Results.Redirect(back + "?errore=cambio#conti"); + } + catch (Anubis.Trading.CapitalException) + { + return Results.Redirect(back + "?errore=capitale#conti"); + } + + return Results.Redirect(back + "?ok=capitale#conti"); + } + + /// An amount as people type it: "1500", "1.500", "1500,50", "1.500,50", "1500.50". + internal static decimal? ParseEuro(string text) + { + var clean = (text ?? "").Replace(" ", "", StringComparison.Ordinal).Replace("€", "", StringComparison.Ordinal); + if (clean.Contains(',', StringComparison.Ordinal)) + { + clean = clean.Replace(".", "", StringComparison.Ordinal).Replace(',', '.'); + } + else if (clean.LastIndexOf('.') is var dot and >= 0 && clean.Length - dot - 1 == 3) + { + clean = clean.Replace(".", "", StringComparison.Ordinal); + } + + return decimal.TryParse(clean, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out var value) + ? Math.Round(value, 2, MidpointRounding.ToZero) + : null; + } + private static async Task BackupAsync(IFormCollection form, AnubisHost host, ILogger logger, CancellationToken ct) { var services = host.Services!; diff --git a/src/Anubis.Server/Overview.cs b/src/Anubis.Server/Overview.cs index b1e0ad1..8a0f0fc 100644 --- a/src/Anubis.Server/Overview.cs +++ b/src/Anubis.Server/Overview.cs @@ -1,9 +1,11 @@ using Anubis.Core; using Anubis.Db; +using Anubis.Trading; namespace Anubis.Server; -public sealed record EquityPoint(DateTimeOffset At, DateOnly Day, decimal Equity, decimal? Benchmark); +/// A point of the total: equity, the capital put in or taken out so far (cumulative) and the time-weighted index. +public sealed record EquityPoint(DateTimeOffset At, DateOnly Day, decimal Equity, decimal? Benchmark, decimal Flows = 0m, decimal? Twr = null); internal sealed record PeriodResult(string Label, decimal Amount, decimal Percent); @@ -11,7 +13,11 @@ internal sealed record NextMove(string Time, string Text); internal sealed record LastAction(string When, string Text); -/// The "Finora" and "Adesso e dopo" halves of the Panoramica (SPEC 13.2, 13.6), read from the database. +/// +/// The "Finora" and "Adesso e dopo" halves of the Panoramica (SPEC 13.2, 13.6), read from the database. One world +/// only, as on the Conti screen: real money when there is a real account, otherwise the simulated one. Results leave +/// out the capital put in or taken out (SPEC 7.5): the amount is net of flows, the percentage is time-weighted. +/// internal sealed record Overview( IReadOnlyList Points, IReadOnlyList Series, @@ -23,7 +29,8 @@ internal sealed record Overview( int PositionsWithoutStop, int OpenOrders, IReadOnlyList Next, - IReadOnlyList Last) + IReadOnlyList Last, + bool CapitalSet = true) { public static readonly IReadOnlyList<(string Key, string Label)> Periods = [("avvio", "Dall'avvio"), ("30", "30 giorni"), ("7", "7 giorni"), ("oggi", "Oggi")]; @@ -31,22 +38,29 @@ internal sealed record Overview( public static async Task LoadAsync(AppServices services, string period, DateTimeOffset now, TimeZoneInfo zone, CancellationToken cancellationToken) { - var (points, positions, withoutStop, orders, journal) = await services.Db.ReadAsync(async s => + var (points, positions, withoutStop, orders, journal, capitalSet) = await services.Db.ReadAsync(async s => { + var environments = await s.QueryAsync("SELECT environment FROM accounts", r => r.Text("environment")).ConfigureAwait(false); + var world = environments.Any(e => TradingEnvironments.World(e) == Worlds.Real) ? Worlds.Real : Worlds.Simulated; + var mine = string.Join(", ", new[] { TradingEnvironments.Simulation, TradingEnvironments.Demo, TradingEnvironments.Live }.Where(e => TradingEnvironments.World(e) == world).Select(e => "'" + e + "'")); var p = await s.QueryAsync( - "SELECT taken_at, equity, benchmark FROM equity_snapshots WHERE scope = 'total' ORDER BY taken_at", - r => (At: r.Moment("taken_at"), Equity: r.Money("equity"), Benchmark: r.MoneyOrNull("benchmark"))).ConfigureAwait(false); - var count = await s.CountAsync("SELECT COUNT(*) FROM positions").ConfigureAwait(false); - var noStop = await s.CountAsync("SELECT COUNT(*) FROM positions WHERE stop_price IS NULL").ConfigureAwait(false); - var open = await s.CountAsync("SELECT COUNT(*) FROM orders WHERE status IN ('new', 'submitted', 'accepted', 'partially_filled')").ConfigureAwait(false); + "SELECT taken_at, equity, benchmark, flows, twr_index FROM equity_snapshots WHERE scope = 'total' AND world = @w ORDER BY taken_at", + r => (At: r.Moment("taken_at"), Equity: r.Money("equity"), Benchmark: r.MoneyOrNull("benchmark"), Flows: r.MoneyOrNull("flows") ?? 0m, Twr: r.MoneyOrNull("twr_index")), + ("w", world)).ConfigureAwait(false); + var held = (await s.QueryAsync($"SELECT p.quantity, p.stop_price FROM positions p JOIN accounts a ON a.id = p.account_id WHERE a.environment IN ({mine})", + r => (Quantity: r.Money("quantity"), Stop: r.MoneyOrNull("stop_price"))).ConfigureAwait(false)).Where(x => x.Quantity > 0m).ToList(); + var open = await s.CountAsync( + $"SELECT COUNT(*) FROM orders o JOIN accounts a ON a.id = o.account_id WHERE a.environment IN ({mine}) " + + "AND o.status IN ('created', 'submitted', 'partially_filled') AND (o.purpose IS NULL OR o.purpose <> 'stop')").ConfigureAwait(false); var j = await s.QueryAsync("SELECT occurred_at, message FROM journal ORDER BY occurred_at DESC LIMIT 4", r => (At: r.Moment("occurred_at"), Text: r.Text("message"))).ConfigureAwait(false); - return (p, count, noStop, open, j); + var capital = await s.CountAsync("SELECT COUNT(*) FROM capital_changes").ConfigureAwait(false); + return (p, held.Count, held.Count(x => x.Stop is null), open, j, capital > 0); }, cancellationToken).ConfigureAwait(false); // One point per day: the last snapshot of each local day. var daily = points - .Select(p => new EquityPoint(p.At, DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(p.At, zone).DateTime), p.Equity, p.Benchmark)) + .Select(p => new EquityPoint(p.At, DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(p.At, zone).DateTime), p.Equity, p.Benchmark, p.Flows, p.Twr)) .GroupBy(p => p.Day) .Select(g => g.Last()) .ToList(); @@ -58,13 +72,19 @@ internal sealed record Overview( if (daily.Count == 0) { - return new Overview([], [], new PeriodResult("", 0, 0), default, 0, [], (int)positions, (int)withoutStop, (int)orders, next, last); + return new Overview([], [], new PeriodResult("", 0, 0), default, 0, [], (int)positions, (int)withoutStop, (int)orders, next, last, capitalSet); } var latest = daily[^1]; EquityPoint Since(int days) => daily.LastOrDefault(p => p.Day <= latest.Day.AddDays(-days)) ?? daily[0]; - PeriodResult Between(string label, EquityPoint start) => - new(label, latest.Equity - start.Equity, start.Equity == 0 ? 0 : (latest.Equity - start.Equity) / start.Equity * 100m); + PeriodResult Between(string label, EquityPoint start) + { + var amount = latest.Equity - start.Equity - (latest.Flows - start.Flows); + var basis = start.Equity + (latest.Flows - start.Flows); + var percent = start.Twr is > 0m && latest.Twr is { } twr ? (twr / start.Twr.Value - 1m) * 100m + : basis == 0 ? 0 : amount / basis * 100m; + return new PeriodResult(label, amount, percent); + } var start = period switch { @@ -80,6 +100,6 @@ internal sealed record Overview( cells.Add(new PeriodResult("Senza bot", lastBenchmark - firstBenchmark, (lastBenchmark - firstBenchmark) / firstBenchmark * 100m)); } - return new Overview(daily, series, Between("", start), start.Day, start.Equity, cells, (int)positions, (int)withoutStop, (int)orders, next, last); + return new Overview(daily, series, Between("", start), start.Day, start.Equity, cells, (int)positions, (int)withoutStop, (int)orders, next, last, capitalSet); } } diff --git a/src/Anubis/Demo/DemoMode.cs b/src/Anubis/Demo/DemoMode.cs index 567542b..8f8494d 100644 --- a/src/Anubis/Demo/DemoMode.cs +++ b/src/Anubis/Demo/DemoMode.cs @@ -12,12 +12,15 @@ namespace Anubis.Demo; /// Demo mode (SPEC 13.1, appendix F): a separate SQLite database in a new temporary folder, never the configured /// one (trap 27), filled with the rows of appendix F; the clock frozen at Friday 9 October 2026, 08:21 Italian /// time; no broker. Values that appendix F gives only as totals go to an aggregates file that only this mode reads. -/// Rows of tables that later phases create (closed trades, news, models) are loaded by those phases. +/// Rows of tables that later phases create (news, models) are loaded by those phases. ///
public static class DemoMode { public const string AggregatesFile = "demo-aggregates.json"; + /// The ECB rate of the demo's morning (F.2): one euro, 1,1601 dollars. + public const decimal UsdRate = 1.1601m; + /// "Adesso" in the demo: Friday 9 October 2026, 08:21 in Rome. public static readonly DateTimeOffset Now = new(2026, 10, 9, 8, 21, 0, TimeSpan.FromHours(2)); @@ -109,34 +112,64 @@ public static class DemoMode await s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, 'OKX Europe', 'okx', 'simulation', 'EUR', @t), (@id2, 'Alpaca', 'alpaca', 'demo', 'USD', @t)", cancellationToken, ("id", okx), ("id2", alpaca), ("t", now)).ConfigureAwait(false); - var strategies = new Dictionary + // F.2, F.3: capital in each account's currency, euro on OKX and dollars on Alpaca at the day's rate. + var strategies = new Dictionary { - ["Trend crypto"] = ("crypto_trend", okx, 4000m), - ["Momentum"] = ("equity_momentum", alpaca, 4500m), - ["Mean reversion"] = ("equity_meanrev", alpaca, 1500m), + ["Trend crypto"] = ("crypto_trend", okx, 4000m, 1905.10m, 1m), + ["Momentum"] = ("equity_momentum", alpaca, 5220.44m, 893.50m, 0.75m), + ["Mean reversion"] = ("equity_meanrev", alpaca, 1740.15m, 1236.71m, 0.25m), }; - foreach (var (name, account, capital) in strategies.Values) + var currencyOf = new Dictionary { [okx] = "EUR", [alpaca] = "USD" }; + foreach (var (name, account, capital, _, share) in strategies.Values) { - await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at) VALUES (@id, @n, @a, 'simulation', @c, @st, @t, @t)", - cancellationToken, ("id", ids.Next()), ("n", name), ("a", account), ("c", capital), ("st", new DbJson("{\"day\":58,\"of\":60}")), ("t", now)).ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, share, state, created_at, updated_at) VALUES (@id, @n, @a, 'simulation', @c, @sh, @st, @t, @t)", + cancellationToken, ("id", ids.Next()), ("n", name), ("a", account), ("c", capital), ("sh", share), ("st", new DbJson("{\"day\":58,\"of\":60}")), ("t", now)) + .ConfigureAwait(false); + } + + var started = now.AddDays(-60); + await s.ExecuteAsync("INSERT INTO fx_rates (id, base, quote, rate_date, rate, source, created_at) VALUES (@id, 'EUR', 'USD', @d, @r, 'ecb', @t)", + cancellationToken, ("id", ids.Next()), ("d", DateOnly.FromDateTime(Now.DateTime).ToString("yyyy-MM-dd", _it)), ("r", UsdRate), ("t", now.AddMinutes(-21))) + .ConfigureAwait(false); + foreach (var (broker, eur, currency, rate, amount) in new[] { ("okx", 4000m, "EUR", 1m, 4000m), ("alpaca", 6000m, "USD", UsdRate, 6960.59m) }) + { + await s.ExecuteAsync("INSERT INTO capital_changes (id, broker, amount_eur, currency, fx_rate, amount, changed_by, created_at) VALUES (@id, @b, @e, @c, @r, @a, 'demo', @t)", + cancellationToken, ("id", ids.Next()), ("b", broker), ("e", eur), ("c", currency), ("r", rate), ("a", amount), ("t", started)).ConfigureAwait(false); } // F.4: the ten open positions. + var held = new List<(string Symbol, Guid Instrument, Guid Account, string Strategy, decimal Quantity, decimal Average, decimal Stop, DateTimeOffset Opened)>(); foreach (var row in Csv("positions.csv").Skip(1)) { var symbol = row[0]; var crypto = symbol.Contains('/', StringComparison.Ordinal); var instrument = ids.Next(); - var (strategy, account, _) = strategies[row[3]]; + var (strategy, account, _, _, _) = strategies[row[3]]; + var opened = now.AddDays(-int.Parse(row[11], _it)); await s.ExecuteAsync("INSERT INTO instruments (id, venue, symbol, name, asset_class, quote_currency, created_at) VALUES (@id, @v, @s, @n, @c, @q, @t)", cancellationToken, ("id", instrument), ("v", crypto ? "okx" : "alpaca"), ("s", symbol), ("n", row[1]), ("c", crypto ? "crypto" : "equity"), ("q", crypto ? "EUR" : "USD"), ("t", now)).ConfigureAwait(false); await s.ExecuteAsync( "INSERT INTO positions (id, account_id, instrument_id, strategy, quantity, average_price, last_price, stop_price, opened_at, created_at, updated_at) VALUES (@id, @a, @i, @s, @q, @p, @l, @st, @o, @t, @t)", cancellationToken, ("id", ids.Next()), ("a", account), ("i", instrument), ("s", strategy), ("q", Number(row[4])), ("p", Number(row[5])), ("l", Number(row[6])), - ("st", Number(row[10])), ("o", now.AddDays(-int.Parse(row[11], _it))), ("t", now)).ConfigureAwait(false); + ("st", Number(row[10])), ("o", opened), ("t", now)).ConfigureAwait(false); + held.Add((symbol, instrument, account, strategy, Number(row[4]), Number(row[5]), Number(row[10]), opened)); } + // Each strategy's cash: the capital given at the start, less what its positions and past trades took. + foreach (var (name, account, capital, cash, _) in strategies.Values) + { + foreach (var (kind, amount, note) in new[] { ("capital", capital, "Capitale affidato"), ("buy", cash - capital, "Saldo di acquisti, vendite e commissioni") }) + { + await s.ExecuteAsync("INSERT INTO cash_ledger (id, account_id, strategy, currency, amount, kind, note, occurred_at, created_at) VALUES (@id, @a, @s, @c, @m, @k, @n, @at, @t)", + cancellationToken, ("id", ids.Next()), ("a", account), ("s", name), ("c", currencyOf[account]), ("m", amount), ("k", kind), ("n", note), + ("at", kind == "capital" ? started : now), ("t", now)).ConfigureAwait(false); + } + } + + await SeedTradesAsync(s, ids, strategies.Values.ToDictionary(v => v.Name, v => v.Account), currencyOf, held, now, cancellationToken).ConfigureAwait(false); + await SeedStopsAndChecksAsync(s, ids, alpaca, held, rome, now, cancellationToken).ConfigureAwait(false); + // F.6: the daily series of the total; accounts and strategies are generated to end on their F.2 and F.3 results. var daily = Csv("daily.csv").Skip(1).Select(r => (Day: DateOnly.ParseExact(r[0], "yyyy-MM-dd", _it), Equity: Number(r[1]), Benchmark: Number(r[2]), Drawdown: Number(r[3]))).ToList(); var total = daily[^1].Equity - 10000m; @@ -151,12 +184,12 @@ public static class DemoMode foreach (var (day, equity, benchmark, drawdown) in daily) { var at = day == DateOnly.FromDateTime(Now.DateTime) ? now : new DateTimeOffset(day.ToDateTime(new TimeOnly(22, 0)), rome.GetUtcOffset(day.ToDateTime(new TimeOnly(22, 0)))); - await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, equity, benchmark, drawdown_pct, created_at) VALUES (@id, @at, 'total', @e, @b, @d, @t)", + await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, world, currency, equity, benchmark, drawdown_pct, created_at) VALUES (@id, @at, 'total', 'simulated', 'EUR', @e, @b, @d, @t)", cancellationToken, ("id", ids.Next()), ("at", at), ("e", equity), ("b", benchmark), ("d", drawdown), ("t", now)).ConfigureAwait(false); foreach (var (scope, account, strategy, start, result) in series) { var value = Math.Round(start + (equity - 10000m) * result / total, 2, MidpointRounding.AwayFromZero); - await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, account_id, strategy, equity, created_at) VALUES (@id, @at, @sc, @a, @st, @e, @t)", + await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, world, currency, account_id, strategy, equity, created_at) VALUES (@id, @at, @sc, 'simulated', 'EUR', @a, @st, @e, @t)", cancellationToken, ("id", ids.Next()), ("at", at), ("sc", scope), ("a", account), ("st", strategy), ("e", value), ("t", now)).ConfigureAwait(false); } } @@ -176,6 +209,116 @@ public static class DemoMode }, cancellationToken).ConfigureAwait(false); } + // F.5: the 41 closed trades. Their net results add up to the "guadagni già incassati" of F.2; the commissions of + // each account go on its first trade. Trades without a symbol in the appendix take one of the strategy's. + private static async Task SeedTradesAsync(DbSession s, IdSource ids, Dictionary accountOf, Dictionary currencyOf, + List<(string Symbol, Guid Instrument, Guid Account, string Strategy, decimal Quantity, decimal Average, decimal Stop, DateTimeOffset Opened)> held, + DateTimeOffset now, CancellationToken cancellationToken) + { + var prices = held.ToDictionary(h => h.Symbol, h => h.Average); + var names = new Dictionary(); + foreach (var (symbol, name, price) in new[] + { + ("TSLA", "Tesla", 250m), ("PG", "Procter & Gamble", 160m), ("LINK/EUR", "Chainlink", 15m), ("V", "Visa", 290m), ("ADA/EUR", "Cardano", 0.6m), + ("AMD", "AMD", 160m), ("UNH", "UnitedHealth", 520m), ("KO", "Coca-Cola", 68m), ("MSFT", "Microsoft", 420m), + }) + { + prices[symbol] = price; + names[symbol] = name; + } + + var instruments = held.ToDictionary(h => h.Symbol, h => h.Instrument); + var fallback = new Dictionary + { + ["crypto_trend"] = ["BTC/EUR", "ETH/EUR", "SOL/EUR"], + ["equity_momentum"] = ["AVGO", "NVDA", "LLY", "JPM", "XOM", "COST"], + ["equity_meanrev"] = ["AAPL", "PG", "V", "KO", "MSFT"], + }; + var fees = new Dictionary { [accountOf["crypto_trend"]] = 14.49m, [accountOf["equity_momentum"]] = Math.Round(0.33m * UsdRate, 2) }; + var rows = Csv("trades.csv").Skip(1).ToList(); + + // In dollars each trade is rounded to the cent; the last one of the account takes the rounding, so the total + // converts back to the euro of F.2 exactly. + var left = rows.GroupBy(r => accountOf[r[1]]).ToDictionary(g => g.Key, g => (Count: g.Count(), Total: Math.Round(g.Sum(r => Number(r[2])) * (currencyOf[g.Key] == "EUR" ? 1m : UsdRate), 2, + MidpointRounding.AwayFromZero))); + for (var i = 0; i < rows.Count; i++) + { + var (strategy, eur) = (rows[i][1], Number(rows[i][2])); + var symbol = rows[i].Length > 3 && rows[i][3].Length > 0 ? rows[i][3] : fallback[strategy][i % fallback[strategy].Length]; + var account = accountOf[strategy]; + if (!instruments.TryGetValue(symbol, out var instrument)) + { + var crypto = symbol.Contains('/', StringComparison.Ordinal); + instrument = ids.Next(); + instruments[symbol] = instrument; + await s.ExecuteAsync("INSERT INTO instruments (id, venue, symbol, name, asset_class, quote_currency, created_at) VALUES (@id, @v, @s, @n, @c, @q, @t)", + cancellationToken, ("id", instrument), ("v", crypto ? "okx" : "alpaca"), ("s", symbol), ("n", names[symbol]), ("c", crypto ? "crypto" : "equity"), ("q", crypto ? "EUR" : "USD"), ("t", now)) + .ConfigureAwait(false); + } + + var currency = currencyOf[account]; + var (count, total) = left[account]; + var realized = count == 1 ? total : currency == "EUR" ? eur : Math.Round(eur * UsdRate, 2, MidpointRounding.AwayFromZero); + left[account] = (count - 1, total - realized); + var fee = fees.Remove(account, out var first) ? first : 0m; + var bought = 600m; + var quantity = Math.Round(bought / prices[symbol], 6); + var closed = now.AddDays(-(rows.Count - i)).AddHours(-3); + await s.ExecuteAsync( + "INSERT INTO trades (id, account_id, instrument_id, strategy, status, opened_at, closed_at, bought_quantity, bought_value, sold_quantity, sold_value, fees, realized, exit_reason, created_at, updated_at) " + + "VALUES (@id, @a, @i, @s, 'closed', @o, @c, @q, @b, @q, @sv, @f, @r, @e, @t, @t)", + cancellationToken, ("id", ids.Next()), ("a", account), ("i", instrument), ("s", strategy), ("o", closed.AddDays(-5)), ("c", closed), ("q", quantity), ("b", bought), + ("sv", bought + realized + fee), ("f", fee), ("r", realized), ("e", realized >= 0m ? "signal" : "stop"), ("t", now)).ConfigureAwait(false); + } + } + + // F.7: the protective stops. On OKX one stop for each coin; on Alpaca a permanent stop on the whole shares, while + // the day stops on the fractions wait for the opening (the market is closed at 08:21). Both accounts were checked + // at 08:20 and agree with the ledger; the keys may trade but not withdraw. + private static async Task SeedStopsAndChecksAsync(DbSession s, IdSource ids, Guid alpaca, + List<(string Symbol, Guid Instrument, Guid Account, string Strategy, decimal Quantity, decimal Average, decimal Stop, DateTimeOffset Opened)> held, + TimeZoneInfo rome, DateTimeOffset now, CancellationToken cancellationToken) + { + DateTimeOffset Local(int daysAgo, int hour, int minute) + { + var local = DateOnly.FromDateTime(Now.DateTime).AddDays(-daysAgo).ToDateTime(new TimeOnly(hour, minute)); + return new DateTimeOffset(local, rome.GetUtcOffset(local)).ToUniversalTime(); + } + + var okxSince = new Dictionary + { + ["BTC/EUR"] = (Local(4, 2, 6), Local(0, 2, 6)), + ["ETH/EUR"] = (Local(2, 9, 14), Local(2, 9, 14)), + ["SOL/EUR"] = (Local(6, 11, 40), Local(6, 11, 40)), + }; + var n = 0; + foreach (var h in held) + { + var whole = decimal.Truncate(h.Quantity); + var onAlpaca = h.Account == alpaca; + if (onAlpaca && whole == 0m) + { + continue; + } + + var (created, updated) = onAlpaca ? (h.Opened, h.Opened) : okxSince[h.Symbol]; + await s.ExecuteAsync( + "INSERT INTO orders (id, account_id, instrument_id, strategy, client_order_id, broker_order_id, side, order_type, quantity, stop_price, status, purpose, time_in_force, " + + "filled_quantity, submitted_at, created_at, updated_at) VALUES (@id, @a, @i, @s, @c, @b, 'sell', 'stop', @q, @st, 'submitted', 'stop', 'gtc', 0, @cr, @cr, @up)", + cancellationToken, ("id", ids.Next()), ("a", h.Account), ("i", h.Instrument), ("s", h.Strategy), ("c", $"ANU-DEMO-STOP-{++n:00}"), ("b", $"demo-{n:00}"), + ("q", onAlpaca ? whole : h.Quantity), ("st", h.Stop), ("cr", created), ("up", updated)).ConfigureAwait(false); + } + + var checkedAt = Local(0, 8, 20); + foreach (var account in held.Select(h => h.Account).Distinct()) + { + await s.ExecuteAsync( + "INSERT INTO account_status (id, account_id, mode, last_reconciled_at, last_outcome, key_can_trade, key_can_withdraw, key_checked_at, created_at, updated_at) " + + "VALUES (@id, @a, 'normal', @at, 'clean', @yes, @no, @at, @t, @t)", + cancellationToken, ("id", ids.Next()), ("a", account), ("at", checkedAt), ("yes", true), ("no", false), ("t", now)).ConfigureAwait(false); + } + } + /// Reads the aggregates file of a demo folder. public static JsonDocument? ReadAggregates(DataDirectory data) { diff --git a/src/Anubis/Trading/Capital.cs b/src/Anubis/Trading/Capital.cs index 4f1bf63..fae9253 100644 --- a/src/Anubis/Trading/Capital.cs +++ b/src/Anubis/Trading/Capital.cs @@ -21,6 +21,15 @@ public static class Strategies public static string BrokerOf(string strategy) => Base.FirstOrDefault(b => b.Name == strategy).Broker ?? throw new ArgumentException($"Unknown strategy '{strategy}'.", nameof(strategy)); + /// The name the user reads (appendix F): short in tables, with the market in legends. + public static string Label(string strategy, bool withMarket = false) => strategy switch + { + CryptoTrend => "Trend crypto", + EquityMomentum => withMarket ? "Momentum azioni" : "Momentum", + EquityMeanrev => withMarket ? "Mean reversion azioni" : "Mean reversion", + _ => strategy, + }; + /// The currency a broker's ledger is kept in: euro on OKX Europe, dollars on Alpaca (SPEC 7.1). public static string CurrencyOf(string broker) => broker == Venues.Alpaca ? "USD" : "EUR"; diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index b6d458e..5b7ed13 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -450,6 +450,37 @@ public sealed partial class TradingService : IDisposable } } + /// The secrets of a broker's practice keys, in the order the settings form asks for them. + public static IReadOnlyList<(string Name, string Label)> KeyFields(string broker) => broker == Venues.Alpaca + ? [("ALPACA_API_KEY_DEMO", "Chiave (API key ID)"), ("ALPACA_API_SECRET_DEMO", "Segreto (secret key)")] + : [("OKX_API_KEY_DEMO", "Chiave (API key)"), ("OKX_API_SECRET_DEMO", "Segreto (secret key)"), ("OKX_API_PASSPHRASE_DEMO", "Passphrase")]; + + /// + /// Asks the broker what new practice keys may do, before they are saved: a key that may withdraw is never kept + /// (SPEC 2.2). Throws when the broker refuses the key or does not answer. + /// + public async Task TestKeysAsync(string broker, IReadOnlyList values, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(values); + foreach (var value in values) + { + Redactor.Register(value); + } + + IBrokerAccount account = broker == Venues.Alpaca + ? new AlpacaTrading(_http, _clock, new AlpacaCredentials(values[0], values[1]), new AlpacaTradingOptions { Environment = TradingEnvironments.Demo }, _consent, _sockets) + : new OkxTrading(_http, _clock, new OkxCredentials(values[0], values[1], values[2]), + new OkxTradingOptions { Environment = TradingEnvironments.Demo, QuoteCurrency = "EUR" }, _consent, _sockets); + try + { + return await account.GetKeyPermissionsAsync(cancellationToken).ConfigureAwait(false); + } + finally + { + (account as IDisposable)?.Dispose(); + } + } + private IBrokerAccount? Build(AccountContext account, AlpacaCredentials? alpaca, OkxCredentials? okx) { switch (account.Environment) diff --git a/tests/Anubis.Tests/AccountsScreenTests.cs b/tests/Anubis.Tests/AccountsScreenTests.cs new file mode 100644 index 0000000..1b45644 --- /dev/null +++ b/tests/Anubis.Tests/AccountsScreenTests.cs @@ -0,0 +1,152 @@ +using System.Net; +using Anubis.Db; +using Anubis.Server; + +namespace Anubis.Tests; + +/// The Conti e posizioni screen and the accounts part of Impostazioni (issue #32). +[TestClass] +public sealed class AccountsScreenTests +{ + [TestMethod] + [TestCategory(Category.Integration)] + public async Task TheDemoShowsTheFiguresOfTheMockup() + { + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]); + var demoRoot = server.Host.Config.Data.Root; + try + { + var page = await server.TextAsync("/conti"); + + // Mockup 02: totals, the two cards, the stops. The ledger computes them from the seeded rows. + foreach (var figure in new[] + { + "10.412,46", "6.671,13", "3.741,33", "4.231,60", "1.905,10", "2.326,50", "+163,45", "+68,15", "14,49", + "6.180,86", "7.170,41", "1.836,23", "2.130,21", "4.344,63", "5.040,20", "+75,83", "+105,03", "0,33", + "+231,60", "+5,79%", "+180,86", "+3,01%", "22,3%", "37,5%", "4,3%", "35,9%", "59,4%", "40,6%", + }) + { + StringAssert.Contains(page, figure, $"Missing {figure} on the Conti page."); + } + + StringAssert.Contains(page, "Attivo, aggiornato oggi alle 02:06"); + StringAssert.Contains(page, "Attivo dal 7 ottobre"); + StringAssert.Contains(page, "5 stop permanenti"); + StringAssert.Contains(page, "6 stop giornalieri"); + StringAssert.Contains(page, "In coda per l'apertura delle 15:30"); + StringAssert.Contains(page, "Registro interno coerente (controllo delle 08:20)"); + StringAssert.Contains(page, "i prelievi sono disattivati"); + StringAssert.Contains(page, "circa 309"); + Assert.IsLessThan(page.IndexOf("Vendi 0,262", StringComparison.Ordinal), page.IndexOf("Vendi 0,0182", StringComparison.Ordinal), "The largest stop comes first."); + + // The filter keeps one account; the CSV has one row per position, for a spreadsheet. + var okx = await server.TextAsync("/conti?conto=okx"); + Assert.IsFalse(okx.Contains("NVDA", StringComparison.Ordinal)); + using var csv = await server.GetAsync("/api/conti/posizioni.csv"); + Assert.AreEqual(HttpStatusCode.OK, csv.StatusCode); + Assert.AreEqual("text/csv", csv.Content.Headers.ContentType?.MediaType); + var bytes = await csv.Content.ReadAsByteArrayAsync(); + CollectionAssert.AreEqual(new byte[] { 0xEF, 0xBB, 0xBF }, bytes[..3], "Excel reads the accents only with the BOM."); + var lines = System.Text.Encoding.UTF8.GetString(bytes[3..]).Split('\n', StringSplitOptions.RemoveEmptyEntries); + Assert.HasCount(11, lines); + StringAssert.StartsWith(lines[1], "BTC/EUR;Bitcoin;okx;crypto_trend;0.0182;68950;71420;EUR;1299.84;44.95;66180;", lines[1]); + + var settings = await server.TextAsync("/impostazioni"); + StringAssert.Contains(settings, "Conti e chiavi"); + StringAssert.Contains(settings, "Nella modalità dimostrativa chiavi e capitale non si cambiano."); + Assert.IsFalse(settings.Contains("/azioni/capitale/", StringComparison.Ordinal), "No capital form in the demo."); + } + finally + { + TempFolder.Delete(demoRoot); + } + } + + [TestMethod] + [TestCategory(Category.Integration)] + public async Task KeysAreAskedToTheBrokerBeforeTheyAreKept() + { + var network = new FakeHttp() + .On(u => u.AbsolutePath == "/api/v5/account/config", _ => FakeHttp.Respond(Fixture.Text("okx-trading/account-config.json"))) + .On(u => u.AbsolutePath == "/v2/account", _ => FakeHttp.Respond(Fixture.Text("alpaca-trading/account.json"))) + .On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound)); + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network, trading: true); + await server.SignInFirstTimeAsync(); + var secrets = server.Host.Services!.Secrets; + + // The documentation's OKX key may withdraw: refused, nothing saved. + using (var okx = await server.PostFormAsync("/impostazioni", "/azioni/chiavi/okx", + ("OKX_API_KEY_DEMO", "test-okx-key"), ("OKX_API_SECRET_DEMO", "test-okx-secret"), ("OKX_API_PASSPHRASE_DEMO", "test-okx-pass"))) + { + Assert.AreEqual("/impostazioni?errore=prelievo#conti", ServerHarness.Location(okx)); + } + + Assert.IsFalse((await secrets.StatusAsync("OKX_API_KEY_DEMO")).IsSet); + + // A missing field never reaches the broker. + using (var empty = await server.PostFormAsync("/impostazioni", "/azioni/chiavi/alpaca", ("ALPACA_API_KEY_DEMO", "test-alpaca-key"), ("ALPACA_API_SECRET_DEMO", " "))) + { + Assert.AreEqual("/impostazioni?errore=chiavi-vuote#conti", ServerHarness.Location(empty)); + } + + // Alpaca keys never withdraw and this account may trade: kept, encrypted, never shown again; the engine restarts with them. + using (var alpaca = await server.PostFormAsync("/impostazioni", "/azioni/chiavi/alpaca", ("ALPACA_API_KEY_DEMO", "test-alpaca-key"), ("ALPACA_API_SECRET_DEMO", "test-alpaca-secret"))) + { + Assert.AreEqual("/impostazioni?ok=chiavi#conti", ServerHarness.Location(alpaca)); + } + + await server.WaitForAsync(HostMode.Ready); + secrets = server.Host.Services!.Secrets; + Assert.IsTrue((await secrets.StatusAsync("ALPACA_API_SECRET_DEMO")).IsSet); + var settings = await server.TextAsync("/impostazioni"); + Assert.IsFalse(settings.Contains("test-alpaca-secret", StringComparison.Ordinal), "A saved key is never shown again."); + StringAssert.Contains(settings, "Impostata"); + // The engine starts in the background after "ready": the paper account appears within moments. + var accounts = new List(); + for (var i = 0; i < 100 && accounts.Count == 0; i++) + { + accounts = [.. await server.Host.Services.Db.ReadAsync(s => s.QueryAsync("SELECT name FROM accounts WHERE environment = 'demo'", r => r.Text("name")))]; + if (accounts.Count == 0) + { + await Task.Delay(100); + } + } + + CollectionAssert.AreEqual(new[] { "Alpaca paper" }, accounts.ToArray()); + + // Capital in euro, as people type it; dollars need the ECB rate first. + using (var capital = await server.PostFormAsync("/impostazioni", "/azioni/capitale/okx", ("euro", "1.500,50"))) + { + Assert.AreEqual("/impostazioni?ok=capitale#conti", ServerHarness.Location(capital)); + } + + using (var usd = await server.PostFormAsync("/impostazioni", "/azioni/capitale/alpaca", ("euro", "2000"))) + { + Assert.AreEqual("/impostazioni?errore=cambio#conti", ServerHarness.Location(usd)); + } + + using (var bad = await server.PostFormAsync("/impostazioni", "/azioni/capitale/okx", ("euro", "molto"))) + { + Assert.AreEqual("/impostazioni?errore=importo#conti", ServerHarness.Location(bad)); + } + + var changes = await server.Host.Services.Db.ReadAsync(s => s.QueryAsync("SELECT broker, amount_eur FROM capital_changes", r => (r.Text("broker"), r.Money("amount_eur")))); + CollectionAssert.AreEqual(new[] { ("okx", 1500.50m) }, changes.ToArray()); + StringAssert.Contains(await server.TextAsync("/impostazioni"), "Trend crypto: quota 100%"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + [DataRow("4000", "4000")] + [DataRow("1.500", "1500")] + [DataRow("1.500,50", "1500.50")] + [DataRow("1500,5", "1500.5")] + [DataRow("1500.50", "1500.50")] + [DataRow(" 2 000 € ", "2000")] + [DataRow("10,999", "10.99")] + [DataRow("-5", null)] + [DataRow("abc", null)] + [DataRow("", null)] + public void AmountsAreReadAsPeopleTypeThem(string text, string? expected) => + Assert.AreEqual(expected is null ? null : decimal.Parse(expected, System.Globalization.CultureInfo.InvariantCulture), Forms.ParseEuro(text)); +} diff --git a/tests/Anubis.Tests/ServerHarness.cs b/tests/Anubis.Tests/ServerHarness.cs index 5b4b595..065a83a 100644 --- a/tests/Anubis.Tests/ServerHarness.cs +++ b/tests/Anubis.Tests/ServerHarness.cs @@ -76,7 +76,7 @@ internal sealed partial class ServerHarness : IAsyncDisposable } public static async Task StartAsync(string platform, IReadOnlyDictionary environment, string? dataDir = null, - string[]? extraArgs = null, bool waitReady = true, HttpMessageHandler? marketHttp = null) + string[]? extraArgs = null, bool waitReady = true, HttpMessageHandler? marketHttp = null, bool trading = false) { var owns = dataDir is null; dataDir ??= TempFolder.Create("server"); @@ -89,6 +89,7 @@ internal sealed partial class ServerHarness : IAsyncDisposable MarketData = marketHttp is not null, MarketHttp = marketHttp, MarketSockets = marketHttp is null ? null : () => new FakeSocket(), + Trading = trading, }); await app.StartAsync().ConfigureAwait(false); var cookies = new CookieContainer(); diff --git a/tools/Anubis.Tasks/Program.cs b/tools/Anubis.Tasks/Program.cs index 38e2ace..2393bb6 100644 --- a/tools/Anubis.Tasks/Program.cs +++ b/tools/Anubis.Tasks/Program.cs @@ -135,7 +135,7 @@ int Screenshots(string[] pages) var folder = Path.Combine(root, "artifacts", "screenshots"); Directory.CreateDirectory(folder); - var targets = pages.Length > 0 ? pages : ["/", "/diario", "/impostazioni"]; + var targets = pages.Length > 0 ? pages : ["/", "/conti", "/diario", "/impostazioni"]; using var shots = Shots.Start(browser); foreach (var page in targets) { diff --git a/tools/Anubis.Tasks/Shots.cs b/tools/Anubis.Tasks/Shots.cs index f119c64..0c7074d 100644 --- a/tools/Anubis.Tasks/Shots.cs +++ b/tools/Anubis.Tasks/Shots.cs @@ -96,6 +96,22 @@ internal sealed class Shots : IDisposable }); Send("Page.navigate", new JsonObject { ["url"] = url }, waitForEvent: "Page.loadEventFired"); Thread.Sleep(500); + + // The whole page, not just the first screen: a page taller than the window grows the window to fit. + var metrics = Send("Page.getLayoutMetrics", new JsonObject()); + var full = (int)Math.Ceiling(metrics["cssContentSize"]?["height"]?.GetValue() ?? height); + if (full > height) + { + Send("Emulation.setDeviceMetricsOverride", new JsonObject + { + ["width"] = width, + ["height"] = full, + ["deviceScaleFactor"] = 2, + ["mobile"] = width < 768, + }); + Thread.Sleep(300); + } + var result = Send("Page.captureScreenshot", new JsonObject { ["format"] = "png" }); File.WriteAllBytes(file, Convert.FromBase64String(result["data"]!.GetValue())); }