diff --git a/docs/adr/0018-scelte-fase-8.md b/docs/adr/0018-scelte-fase-8.md index ad92a9d..1f5b25c 100644 --- a/docs/adr/0018-scelte-fase-8.md +++ b/docs/adr/0018-scelte-fase-8.md @@ -62,3 +62,13 @@ Con poche migliaia di esempi e una ventina di indizi bastano: un addestramento d - Le strategie senza frequenza di base non addestrano: nessuno potrebbe stimarle. **11. Avvio (11.5).** I 300 segnali sono quelli con un esito. Calibrazione e guadagno si misurano sulle stime in carica al momento di ogni segnale, pesate per la maturazione (11.4); il guadagno solo sui segnali di strategie che in quel momento avevano capitale (stadio diverso da osservazione). Una volta attivato, il modello resta attivo: lo ferma la messa da parte. + +**12. Scostamento (11.6).** Il primo controllo notturno di ogni mese confronta, per fascia di liquidità (azioni; BTC, ETH e SOL; altre crypto), lo scostamento delle esecuzioni di conti di prova e reali degli ultimi 365 giorni. La fascia è l’unica variabile della regressione: il suo risultato è la media, con un intervallo al 95% a blocchi. +- Servono 30 esecuzioni. Gli stop scattati non contano: il salto di prezzo è già nel modo in cui simulatore e backtest li eseguono. +- Sale da sola solo se tutto l’intervallo sta sopra la stima in uso; scende solo su esecuzioni con soldi veri, con tutto l’intervallo sotto, e solo dopo la conferma nel Laboratorio. La stima si arrotonda per eccesso a mezzo punto base e non scende sotto mezzo punto. Una proposta non confermata scade il mese dopo. +- Lo scostamento si misura dal prezzo medio, quindi contiene anche la metà della forbice; il simulatore parte già dal denaro o dalla lettera: così conta un po’ di più, dal lato prudente. +- Un test nel Laboratorio scrive nel piano la tabella in uso, se diversa da quella di partenza: i piani già scritti restano identici. Le etichette (punto 3) e gli esiti di qualifica usano sempre la tabella di partenza: gli esempi restano confrontabili negli anni e il “previsto” di 12.3 resta quello della qualifica. + +**13. Impatto delle notizie.** Per tipo di evento (parole chiave dei casi gravi, poi il tipo detto dal modello linguistico), il rendimento medio a 1 e a 5 chiusure dalla prima chiusura dopo la pubblicazione, sugli strumenti collegati. Solo informativa. + +**14. Scoperte.** Le domande sono fisse nel codice (agitazione dei prezzi, fase del mercato, ampiezza, volumi, notizie molto negative, paura e avidità estreme, VIX, giorno della settimana), per strategia: il bot non ne cerca altre. L’errore conta come un caso solo ciò che è deciso nello stesso mese. Sotto i 100 casi basta che la differenza superi 1,96 errori e il giudizio dice da solo quanto vale; da 100 in su la soglia si alza con il numero di domande fatte. “Non conta” si dice solo con almeno 100 casi. diff --git a/src/Anubis.Server/Components/Pages/Laboratorio.razor b/src/Anubis.Server/Components/Pages/Laboratorio.razor index 688cc29..4356201 100644 --- a/src/Anubis.Server/Components/Pages/Laboratorio.razor +++ b/src/Anubis.Server/Components/Pages/Laboratorio.razor @@ -5,7 +5,9 @@ @inject IClock Clock @using Anubis.Backtest @using Anubis.Data +@using Anubis.Learning @using Anubis.Strategies +@using Anubis.Trading Laboratorio · Anubis @@ -173,10 +175,47 @@

Stime di costo da confermare

-
-

Nessuna stima da confermare.

-

Quando le esecuzioni con soldi veri diranno che lo scostamento è più basso di quello previsto, la nuova stima aspetterà qui la tua conferma. Arrivano con la Fase 8.

-
+

Scostamento contato da simulatore e backtest: @string.Join("; ", SlippageTiers.All.Select(t => SlippageTiers.Label(t) + " " + Bp(_table.Of(t)))). Ogni mese si confronta con le esecuzioni ottenute dai broker, mai con quelle del simulatore. Una stima sale da sola; scende solo se viene da soldi veri e la confermi tu.

+ @if (_costs.Where(c => c.Status == CostStatuses.Pending).ToList() is { Count: > 0 } pending) + { + @foreach (var c in pending) + { +
+

@Capital(SlippageTiers.Label(c.Tier)): da @Bp(c.PreviousBp) a @Bp(c.Bp). Misurati @Bp(c.MeasuredBp) su @c.Cases esecuzioni con soldi veri (tra @Bp(c.LowBp) e @Bp(c.HighBp) al 95%).

+
+
+
+ } + } + else + { +
+

Nessuna stima da confermare.

+

Quando le esecuzioni con soldi veri diranno che lo scostamento è più basso di quello previsto, la nuova stima aspetterà qui la tua conferma.

+
+ } + @if (_costs.Where(c => c.Status != CostStatuses.Pending).Reverse().Take(10).ToList() is { Count: > 0 } past) + { +
+ + + + + @foreach (var c in past) + { + + + + + + + + + } + +
Stime di scostamento già decise
QuandoStrumentiPrimaStimaEsecuzioniEsito
@Format.ShortDate(c.DecidedAt ?? c.CreatedAt, Shell.Now, Shell.Zone)@Capital(SlippageTiers.Label(c.Tier))@Bp(c.PreviousBp)@Bp(c.Bp)@c.Cases@Outcome(c.Status)
+
+ }
@code { @@ -188,6 +227,8 @@ private DateOnly _from; private DateOnly _to; private IReadOnlyList _research = []; + private IReadOnlyList _costs = []; + private SlippageTable _table = SlippageTable.Standard; [CascadingParameter] public HttpContext? HttpContext { get; set; } @@ -204,6 +245,9 @@ var services = Host.Services!; _lab = services.Lab; _trials = await new TrialStore(services.Db, Clock).ListAsync(100, ct); + var costs = new CostBook(services.Db, Clock); + _costs = await costs.ListAsync(ct); + _table = await costs.TableAsync(ct); _running = _trials.Any(t => !t.IsFinished); _family = StrategyCatalog.Find(Strategia ?? "") ?? StrategyCatalog.All[0]; var today = DateOnly.FromDateTime(Clock.UtcNow.UtcDateTime); @@ -217,6 +261,7 @@ _message = Errore switch { null => null, + "stima" => "Quella stima non aspetta più una conferma.", "motore" => "Il laboratorio non è attivo in questo momento: riprova tra poco.", TrialRequestErrors.Strategy => "Strategia sconosciuta: scegline una dall'elenco.", TrialRequestErrors.Source => "Scegli da dove prendere i dati e, per le barre raccolte, il mercato.", @@ -229,6 +274,18 @@ }; } + private static string Bp(decimal bp) => Format.Quantity(Math.Round(bp, 1)) + " punti base"; + + private static string Capital(string text) => char.ToUpper(text[0], System.Globalization.CultureInfo.GetCultureInfo("it-IT")) + text[1..]; + + private static string Outcome(string status) => status switch + { + CostStatuses.Applied => "Salita da sola", + CostStatuses.Confirmed => "Confermata da te", + CostStatuses.Refused => "Rifiutata da te", + _ => "Superata dal mese dopo", + }; + private string Research() => _research.Count == 0 ? "Lo storico di ricerca è vuoto: lo riempie la raccolta dei dati." : "Nello storico di ricerca: " + LabText.Symbols(_research) + "."; diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs index 5922316..808001b 100644 --- a/src/Anubis.Server/Forms.cs +++ b/src/Anubis.Server/Forms.cs @@ -41,6 +41,7 @@ internal static partial class Forms signed.MapPost("/segnale-di-vita/togli", RemoveHeartbeatAsync); signed.MapPost("/assenza/{id:guid}/vista", AbsenceSeenAsync); signed.MapPost("/laboratorio", PlanTrialAsync); + signed.MapPost("/stime-di-costo/{id:guid}/{choice}", DecideCostAsync); signed.MapPost("/strategie/{strategy}/{choice}", StrategyStageAsync); signed.MapPost("/rischio/limiti", SetLimitsAsync); signed.MapPost("/rischio/{key}", SetRiskSettingAsync); @@ -764,6 +765,24 @@ internal static partial class Forms } } + /// A lower slippage estimate waits for the user (SPEC 11.6). + private static async Task DecideCostAsync(Guid id, string choice, AnubisHost host, HttpContext context, CancellationToken ct) + { + if (host.IsDemo || host.Services is not { } services || choice is not ("conferma" or "rifiuta")) + { + return Results.Redirect("/laboratorio?errore=motore#stime"); + } + + var book = new Anubis.Learning.CostBook(services.Db, host.Clock); + var done = await book.DecideAsync(id, choice == "conferma", context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false); + if (done && services.Trading is { } trading) + { + await trading.RefreshCostsAsync(ct).ConfigureAwait(false); + } + + return Results.Redirect(done ? "/laboratorio#stime" : "/laboratorio?errore=stima#stime"); + } + private static DateOnly? ParseDay(string text) => DateOnly.TryParseExact(text, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var day) ? day : null; diff --git a/src/Anubis/Backtest/Costs.cs b/src/Anubis/Backtest/Costs.cs index 7f26ec2..9bc6475 100644 --- a/src/Anubis/Backtest/Costs.cs +++ b/src/Anubis/Backtest/Costs.cs @@ -20,6 +20,9 @@ public sealed record CostModel(decimal Multiplier = 1m) { public static CostModel Standard { get; } = new(); + /// The slippage in force when the test was planned (SPEC 11.6). + public SlippageTable Slippage { get; init; } = SlippageTable.Standard; + /// The price list of the venue where the instrument would trade. Research archives trade like OKX. public static PaperOptions PriceList(InstrumentSpec spec) { @@ -27,7 +30,7 @@ public sealed record CostModel(decimal Multiplier = 1m) return spec.Venue == Venues.Alpaca ? PaperOptions.Alpaca() : PaperOptions.Okx(spec.QuoteCurrency); } - public decimal SlippageRate(InstrumentSpec spec) => PaperBroker.SlippageBp(spec) / 10_000m * Multiplier; + public decimal SlippageRate(InstrumentSpec spec) => Slippage.Bp(spec) / 10_000m * Multiplier; /// The price paid or received: the reference moved by the slippage, rounded to the tick against us. public decimal ExecutionPrice(InstrumentSpec spec, OrderSide side, decimal reference) diff --git a/src/Anubis/Backtest/Laboratory.cs b/src/Anubis/Backtest/Laboratory.cs index 0309736..24a98cc 100644 --- a/src/Anubis/Backtest/Laboratory.cs +++ b/src/Anubis/Backtest/Laboratory.cs @@ -5,6 +5,7 @@ using Anubis.Core; using Anubis.Data; using Anubis.Db; using Anubis.Strategies; +using Anubis.Trading; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -78,14 +79,14 @@ public sealed partial class Laboratory : IDisposable /// Checks the request, writes the plan and queues the trial. The plan is final from here on. public async Task PlanAsync(TrialRequest request, CancellationToken cancellationToken) { - var (plan, variants) = BuildPlan(request, _clock.UtcNow); + var (plan, variants) = BuildPlan(request, _clock.UtcNow, await new Anubis.Learning.CostBook(_db, _clock).TableAsync(cancellationToken).ConfigureAwait(false)); var trial = await Trials.PlanAsync(plan, variants, cancellationToken).ConfigureAwait(false); await _queue.Writer.WriteAsync(trial.Id, cancellationToken).ConfigureAwait(false); return trial; } /// The plan of a request: the family's own grid where the request gives none, the default costs, checks and thresholds. - public static (TrialPlan Plan, int Variants) BuildPlan(TrialRequest request, DateTimeOffset now) + public static (TrialPlan Plan, int Variants) BuildPlan(TrialRequest request, DateTimeOffset now, SlippageTable? slippage = null) { ArgumentNullException.ThrowIfNull(request); var family = StrategyCatalog.Find(request.Strategy) ?? throw new TrialRequestException(TrialRequestErrors.Strategy, "Strategia sconosciuta."); @@ -146,6 +147,7 @@ public sealed partial class Laboratory : IDisposable now) { ReferenceShare = StrategyPipeline.DefaultShare(family.Id), + Slippage = slippage == SlippageTable.Standard ? null : slippage, }; var variants = ParameterGrid.Of(family, plan.Grid).Count; if (variants == 0) diff --git a/src/Anubis/Backtest/Report.cs b/src/Anubis/Backtest/Report.cs index 94201cc..5612949 100644 --- a/src/Anubis/Backtest/Report.cs +++ b/src/Anubis/Backtest/Report.cs @@ -3,6 +3,7 @@ using System.Globalization; using System.Text.Json; using Anubis.Data; using Anubis.Strategies; +using Anubis.Trading; namespace Anubis.Backtest; @@ -119,7 +120,7 @@ public static class TrialRunner } // The strategy goes through its correctives and the risk engine; buy and hold, the comparison, never does. - var plain = new BacktestOptions { InitialCapital = plan.InitialCapital, From = plan.Data.From, To = plan.Data.To }; + var plain = new BacktestOptions { InitialCapital = plan.InitialCapital, From = plan.Data.From, To = plan.Data.To, Costs = new CostModel { Slippage = plan.Slippage ?? SlippageTable.Standard } }; var options = StrategyPipeline.For(family.Id, data, plain, plan.ReferenceShare); var runs = new BacktestRun[variants.Count]; for (var i = 0; i < variants.Count; i++) @@ -141,7 +142,7 @@ public static class TrialRunner var costs = new List(); foreach (var multiplier in plan.CostMultipliers.Distinct().Order()) { - var costed = multiplier == 1m ? run : BacktestEngine.Run(family.Create(chosen.Parameters), data, options with { Costs = new CostModel(multiplier) }); + var costed = multiplier == 1m ? run : BacktestEngine.Run(family.Create(chosen.Parameters), data, options with { Costs = options.Costs with { Multiplier = multiplier } }); var m = multiplier == 1m ? metrics : BacktestMetrics.Of(costed, data.PeriodsPerYear); costs.Add(new ReportCosts(multiplier, costed.NetResult, m.TotalReturn, m.Sharpe, m.MaxDrawdown, costed.Fees)); } diff --git a/src/Anubis/Backtest/Trials.cs b/src/Anubis/Backtest/Trials.cs index 96cd14a..916a72e 100644 --- a/src/Anubis/Backtest/Trials.cs +++ b/src/Anubis/Backtest/Trials.cs @@ -4,6 +4,7 @@ using System.Text.Json; using System.Text.Json.Serialization; using Anubis.Core; using Anubis.Db; +using Anubis.Trading; namespace Anubis.Backtest; @@ -68,6 +69,9 @@ public sealed record TrialPlan( /// public decimal? ReferenceShare { get; init; } + /// The slippage in force when the plan was written (SPEC 11.6); null for the standard one. + public SlippageTable? Slippage { get; init; } + public static readonly JsonSerializerOptions Json = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, diff --git a/src/Anubis/Db/Migrations/0013_cost_estimates.sql b/src/Anubis/Db/Migrations/0013_cost_estimates.sql new file mode 100644 index 0000000..be77cbb --- /dev/null +++ b/src/Anubis/Db/Migrations/0013_cost_estimates.sql @@ -0,0 +1,20 @@ +-- The slippage estimates of SPEC 11.6 (issue #65): one row for each change proposed by the monthly regression on the +-- executions of a broker. A rise is applied at once; a fall, only from real money, waits for the user. + +CREATE TABLE cost_estimates ( + id {uuid} PRIMARY KEY, + tier TEXT NOT NULL, + status TEXT NOT NULL, + previous_bp {money} NOT NULL, + bp {money} NOT NULL, + measured_bp {money} NOT NULL, + low_bp {money} NOT NULL, + high_bp {money} NOT NULL, + cases INTEGER NOT NULL, + decided_by TEXT, + decided_at {timestamp}, + created_at {timestamp} NOT NULL, + updated_at {timestamp} NOT NULL +){strict}; + +CREATE INDEX cost_estimates_created ON cost_estimates (created_at); diff --git a/src/Anubis/Learning/CostBook.cs b/src/Anubis/Learning/CostBook.cs new file mode 100644 index 0000000..90165a3 --- /dev/null +++ b/src/Anubis/Learning/CostBook.cs @@ -0,0 +1,209 @@ +using System.Globalization; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.Notifications; +using Anubis.Trading; + +namespace Anubis.Learning; + +public static class CostStatuses +{ + /// In force since it was made: a rise. + public const string Applied = "applied"; + + /// A fall that waits for the user. + public const string Pending = "pending"; + + /// A fall in force because the user confirmed it. + public const string Confirmed = "confirmed"; + + public const string Refused = "refused"; + + /// A proposal that a later month replaced before the user decided. + public const string Replaced = "replaced"; +} + +public sealed record CostEstimate(Guid Id, string Tier, string Status, decimal PreviousBp, decimal Bp, decimal MeasuredBp, decimal LowBp, decimal HighBp, int Cases, DateTimeOffset CreatedAt, + string? DecidedBy = null, DateTimeOffset? DecidedAt = null); + +/// An execution obtained from a broker: never the internal simulator, which would give back its own guess. +public sealed record PaidFill(string Tier, double SlippageBp, bool RealMoney, DateTimeOffset At); + +/// What the executions of a tier propose. +public sealed record CostProposal(string Tier, bool Rise, decimal Bp, decimal Measured, decimal Low, decimal High, int Cases); + +/// +/// The monthly regression of SPEC 11.6: the slippage of the executions against their tier. With the tier alone among its +/// variables its answer is the mean of each, with an interval that keeps neighbours together. +/// +public static class CostRegression +{ + /// Fewer executions than this in a tier say nothing. + public const int MinCases = 30; + + /// The estimates move by half basis points, always up to the next: cautious. + public const decimal Step = 0.5m; + + /// + /// What the executions propose against the table in force. A rise needs the whole interval above what is in force, on + /// any broker account; a fall the whole interval below it, on real money alone. + /// + public static IReadOnlyList Of(IReadOnlyList fills, SlippageTable table) + { + ArgumentNullException.ThrowIfNull(fills); + ArgumentNullException.ThrowIfNull(table); + var proposals = new List(); + foreach (var tier in SlippageTiers.All) + { + var current = table.Of(tier); + var all = fills.Where(f => f.Tier == tier).OrderBy(f => f.At).ToList(); + if (Fit(all) is { } seen && seen.Low > (double)current) + { + proposals.Add(Proposed(tier, true, seen, all.Count)); + continue; + } + + var real = all.Where(f => f.RealMoney).ToList(); + if (Fit(real) is { } paid && paid.High < (double)current && Proposed(tier, false, paid, real.Count) is var fall && fall.Bp < current) + { + proposals.Add(fall); + } + } + + return proposals; + } + + private static (double Mean, double Low, double High)? Fit(List fills) + { + if (fills.Count < MinCases) + { + return null; + } + + var values = fills.Select(f => f.SlippageBp).ToList(); + var (low, high) = Judge.Interval(values, [.. values.Select(_ => 1.0)], 0.95); + return (values.Average(), low, high); + } + + private static CostProposal Proposed(string tier, bool rise, (double Mean, double Low, double High) fit, int cases) => + new(tier, rise, Math.Max(Step, Math.Ceiling((decimal)fit.Mean / Step) * Step), Rounded(fit.Mean), Rounded(fit.Low), Rounded(fit.High), cases); + + private static decimal Rounded(double value) => Math.Round((decimal)value, 4); +} + +/// The slippage estimates: the table in force, the monthly run, what waits for the user (SPEC 11.6). +public sealed class CostBook(Database db, IClock clock) +{ + public const string StateKey = "cost_month"; + + /// How far back the executions count. + public static readonly TimeSpan Window = TimeSpan.FromDays(365); + + private static readonly CultureInfo It = CultureInfo.GetCultureInfo("it-IT"); + + private sealed record Month(string Name); + + public async Task TableAsync(CancellationToken cancellationToken) => + TableOf(await ListAsync(cancellationToken).ConfigureAwait(false)); + + /// Every estimate, oldest first. + public Task> ListAsync(CancellationToken cancellationToken) => db.ReadAsync(ListAsync, cancellationToken); + + private static Task> ListAsync(DbSession s) => + s.QueryAsync("SELECT id, tier, status, previous_bp, bp, measured_bp, low_bp, high_bp, cases, decided_by, decided_at, created_at FROM cost_estimates ORDER BY created_at, id", + r => new CostEstimate(r.Id("id"), r.Text("tier"), r.Text("status"), r.Money("previous_bp"), r.Money("bp"), r.Money("measured_bp"), r.Money("low_bp"), r.Money("high_bp"), + (int)r.Number("cases"), r.Moment("created_at"), r.TextOrNull("decided_by"), r.MomentOrNull("decided_at"))); + + private static SlippageTable TableOf(IEnumerable estimates) + { + var table = SlippageTable.Standard; + foreach (var e in estimates.Where(e => e.Status is CostStatuses.Applied or CostStatuses.Confirmed && SlippageTiers.All.Contains(e.Tier)).OrderBy(e => e.DecidedAt ?? e.CreatedAt)) + { + table = table.With(e.Tier, e.Bp); + } + + return table; + } + + /// The run of the month: once for each month, at the first night it finds. True when it ran. + public async Task MonthAsync(CancellationToken cancellationToken) + { + var now = clock.UtcNow; + var month = Zones.DayIn(now, Zones.Rome).ToString("yyyy-MM", CultureInfo.InvariantCulture); + if ((await new LearningStore(db, clock).StateAsync(StateKey, cancellationToken).ConfigureAwait(false))?.Name == month) + { + return false; + } + + var fills = await FillsAsync(now - Window, cancellationToken).ConfigureAwait(false); + await db.WriteAsync(async s => + { + var table = TableOf(await ListAsync(s).ConfigureAwait(false)); + + // A proposal of an earlier month still open is out of date, whatever this month says. + await s.ExecuteAsync("UPDATE cost_estimates SET status = @r, updated_at = @now WHERE status = @p", cancellationToken, + ("r", CostStatuses.Replaced), ("now", now), ("p", CostStatuses.Pending)).ConfigureAwait(false); + foreach (var proposal in CostRegression.Of(fills, table)) + { + await ProposeAsync(s, proposal, table.Of(proposal.Tier), now, cancellationToken).ConfigureAwait(false); + } + + await LearningStore.SaveStateAsync(s, clock, StateKey, new Month(month), cancellationToken).ConfigureAwait(false); + }, cancellationToken).ConfigureAwait(false); + return true; + } + + private async Task ProposeAsync(DbSession s, CostProposal p, decimal current, DateTimeOffset now, CancellationToken cancellationToken) + { + await s.ExecuteAsync( + "INSERT INTO cost_estimates (id, tier, status, previous_bp, bp, measured_bp, low_bp, high_bp, cases, created_at, updated_at) VALUES (@id, @t, @st, @prev, @bp, @m, @l, @h, @n, @now, @now)", + cancellationToken, ("id", Ids.NewId(clock)), ("t", p.Tier), ("st", p.Rise ? CostStatuses.Applied : CostStatuses.Pending), ("prev", current), ("bp", p.Bp), ("m", p.Measured), + ("l", p.Low), ("h", p.High), ("n", p.Cases), ("now", now)).ConfigureAwait(false); + var what = string.Create(It, $"Scostamento misurato su {p.Cases} esecuzioni ({SlippageTiers.Label(p.Tier)}): {p.Measured:0.0} punti base invece dei {current:0.0} previsti."); + if (p.Rise) + { + await Diary.WriteAsync(s, clock, DiaryKinds.Learning, "cost_raised", string.Create(It, $"{what} Da ora simulatore e backtest ne contano {p.Bp:0.0}."), null, cancellationToken).ConfigureAwait(false); + return; + } + + var text = what + " La stima più bassa aspetta la tua conferma nel Laboratorio."; + await Diary.WriteAsync(s, clock, DiaryKinds.Learning, "cost_pending", text, null, cancellationToken).ConfigureAwait(false); + await NotificationSender.EnqueueAsync(s, clock, "cost_pending", text, cancellationToken).ConfigureAwait(false); + } + + /// The user confirms or refuses a fall. False when it is not waiting any more, or it would not be a fall now. + public Task DecideAsync(Guid id, bool accept, string user, CancellationToken cancellationToken) => + db.WriteAsync(async s => + { + var rows = await ListAsync(s).ConfigureAwait(false); + if (rows.FirstOrDefault(e => e.Id == id) is not { Status: CostStatuses.Pending } row || (accept && row.Bp >= TableOf(rows).Of(row.Tier))) + { + return false; + } + + await s.ExecuteAsync("UPDATE cost_estimates SET status = @st, decided_by = @u, decided_at = @now, updated_at = @now WHERE id = @id AND status = @p", cancellationToken, + ("st", accept ? CostStatuses.Confirmed : CostStatuses.Refused), ("u", user), ("now", clock.UtcNow), ("id", id), ("p", CostStatuses.Pending)).ConfigureAwait(false); + var text = string.Create(It, $"{(accept ? "Confermata" : "Rifiutata")} da te la stima di scostamento più bassa ({SlippageTiers.Label(row.Tier)}): da {row.PreviousBp:0.0} a {row.Bp:0.0} punti base."); + await Diary.WriteAsync(s, clock, DiaryKinds.Learning, accept ? "cost_confirmed" : "cost_refused", text, null, cancellationToken).ConfigureAwait(false); + return true; + }, cancellationToken); + + /// + /// The executions obtained from a broker since . A stop that jumped a gap is not slippage: the + /// simulator and the backtest already fill it at the price after the gap. + /// + public async Task> FillsAsync(DateTimeOffset since, CancellationToken cancellationToken) + { + var rows = await db.ReadAsync(s => s.QueryAsync( + "SELECT f.slippage_bp, f.executed_at, a.environment, i.symbol, i.asset_class, i.base_currency FROM fills f JOIN accounts a ON a.id = f.account_id JOIN instruments i ON i.id = f.instrument_id LEFT JOIN orders o ON o.id = f.order_id " + + "WHERE f.slippage_bp IS NOT NULL AND f.executed_at >= @f AND a.environment <> @sim AND (o.purpose IS NULL OR o.purpose <> @stop) ORDER BY f.executed_at, f.id", + r => (Bp: r.Money("slippage_bp"), At: r.Moment("executed_at"), Environment: r.Text("environment"), Symbol: r.Text("symbol"), Class: r.Text("asset_class"), Base: r.TextOrNull("base_currency")), + ("f", since), ("sim", TradingEnvironments.Simulation), ("stop", Wire.Text(OrderPurpose.Stop))), cancellationToken).ConfigureAwait(false); + return + [ + .. rows.Where(r => r.Environment is TradingEnvironments.Demo or TradingEnvironments.Live) + .Select(r => new PaidFill(SlippageTiers.Of(r.Class, r.Base, r.Symbol), (double)r.Bp, r.Environment == TradingEnvironments.Live, r.At)), + ]; + } +} diff --git a/src/Anubis/Learning/Discoveries.cs b/src/Anubis/Learning/Discoveries.cs new file mode 100644 index 0000000..8494a6b --- /dev/null +++ b/src/Anubis/Learning/Discoveries.cs @@ -0,0 +1,302 @@ +using System.Globalization; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.News; +using Anubis.Trading; + +namespace Anubis.Learning; + +/// A relation in plain Italian, with what supports it (SPEC 11.6). +public sealed record Discovery(string Title, string Detail, int Cases) +{ + /// The judgement on the number of cases, with the words of SPEC 11.6. + public string Trust => TrustOf(Cases); + + public static string TrustOf(int cases) => cases < 20 ? "troppo pochi per fidarsi" : cases < 100 ? "un indizio discreto" : "conclusione solida"; +} + +/// What happened to the prices after the news of a kind: the mean return one and five closes later. +public sealed record NewsImpact(string Kind, int Cases, double OneDay, double FiveDays) +{ + public string Trust => Discovery.TrustOf(Cases); +} + +/// The discoveries as they were last computed. +public sealed record DiscoverySet +{ + public const string Key = "discoveries"; + + public DateTimeOffset At { get; init; } + + public IReadOnlyList Found { get; init; } = []; + + public IReadOnlyList News { get; init; } = []; +} + +/// +/// The relations between the clues and the outcomes (SPEC 11.6). The questions are fixed here, before any number: the bot +/// answers these and does not go looking for others, because among many relations some always look good by chance. +/// +public static class DiscoveryFinder +{ + /// A group smaller than this is not worth a sentence. + public const int MinGroup = 10; + + public const int MaxShown = 8; + + private const double Clear = 1.96; + + private static readonly CultureInfo It = CultureInfo.GetCultureInfo("it-IT"); + + /// A question: the examples in which the condition held against all the others of the strategy. + private sealed record Question(string Clue, Func Holds, string Less, string More, string Neither); + + private static readonly IReadOnlyList Questions = + [ + new(Clues.VolatilityRatio, v => v >= 1.5, "{0} riescono meno quando i prezzi sono molto più agitati del solito", "{0} riescono di più quando i prezzi sono molto più agitati del solito", + "Che i prezzi siano più agitati del solito non conta per {1}"), + new(Clues.MarketTrend, v => v < 0, "{0} riescono meno quando il mercato è in discesa", "{0} riescono di più quando il mercato è in discesa", "La fase del mercato non conta per {1}"), + new(Clues.Breadth, v => v < 0.5, "{0} riescono meno quando sale meno di metà del mercato", "{0} riescono di più quando sale meno di metà del mercato", + "Quanta parte del mercato sale non conta per {1}"), + new(Clues.Volume, v => v >= 1.5, "{0} riescono meno con scambi molto sopra la norma", "{0} riescono di più con scambi molto sopra la norma", "I volumi scambiati non contano per {1}"), + new(Clues.Tone3, v => v <= -0.6, "Dopo notizie molto negative {1} riescono meno", "Dopo notizie molto negative {1} riescono di più", "Le notizie molto negative non contano per {1}"), + new(Clues.FearGreed, v => v < 25, "{0} riescono meno quando c'è paura estrema", "{0} riescono di più quando c'è paura estrema", "La paura estrema non conta per {1}"), + new(Clues.FearGreed, v => v > 75, "{0} riescono meno quando c'è avidità estrema", "{0} riescono di più quando c'è avidità estrema", "L'avidità estrema non conta per {1}"), + new(Clues.Vix, v => v > 30, "{0} riescono meno quando il VIX è nel panico", "{0} riescono di più quando il VIX è nel panico", "Il panico del VIX non conta per {1}"), + ]; + + private static readonly string[] Days = ["domenica", "lunedì", "martedì", "mercoledì", "giovedì", "venerdì", "sabato"]; + + public static string SignalsOf(string strategy) => strategy switch + { + StrategyNames.CryptoTrend => "i segnali di trend sulle crypto", + StrategyNames.EquityMomentum => "i segnali sulle azioni più forti", + StrategyNames.EquityMeanrev => "i rimbalzi sulle azioni", + _ => "i segnali", + }; + + /// The relations that hold, and those that surely do not, the clearest first. + public static IReadOnlyList Of(IReadOnlyList examples) + { + ArgumentNullException.ThrowIfNull(examples); + var answers = new List<(double Z, int Group, Func Say)>(); + foreach (var strategy in examples.Where(e => e.IsLabelled).GroupBy(e => e.Strategy, StringComparer.Ordinal).OrderBy(g => g.Key, StringComparer.Ordinal)) + { + var signals = SignalsOf(strategy.Key); + foreach (var q in Questions) + { + var known = strategy.Where(e => e.Features.ContainsKey(q.Clue)).ToList(); + if (Compare(known, e => q.Holds(e.Features[q.Clue])) is { } c) + { + answers.Add((Math.Abs(c.Z), c.Group, bar => Sentence(c, signals, q.Less, q.More, q.Neither, bar))); + } + } + + // The weekday: the day that stands out most, against a bar raised because there are seven of them. + var days = Enumerable.Range(0, 7).Select(d => (Day: d, Found: Compare([.. strategy], e => (int)e.Day.DayOfWeek == d))).Where(x => x.Found is not null).ToList(); + if (days.Count >= 2) + { + var (day, found) = days.MaxBy(x => Math.Abs(x.Found!.Z)); + var c = found! with { Corrected = days.Count }; + answers.Add((Math.Abs(c.Z), c.Group, bar => Sentence(c, signals, "{0} riescono meno di " + Days[day], "{0} riescono di più di " + Days[day], "Il giorno della settimana non conta per {1}", bar))); + } + } + + var bar = answers.Count; + return + [ + .. answers.Select(a => (a.Z, Text: a.Say(bar))).Where(a => a.Text is not null).OrderByDescending(a => a.Z).Select(a => a.Text!).Take(MaxShown), + ]; + } + + private sealed record Comparison(double Z, int Group, int All, double InGroup, double Others) + { + /// How many comparisons hide behind this one. + public int Corrected { get; init; } = 1; + } + + /// + /// The difference between the shares of winners, over a standard error that counts as one the operations decided in the + /// same month: many coins move together, and a hundred of them in a week are not a hundred proofs. + /// + private static Comparison? Compare(IReadOnlyList examples, Func holds) + { + var inside = examples.Where(holds).ToList(); + var outside = examples.Where(e => !holds(e)).ToList(); + if (inside.Count < MinGroup || outside.Count < MinGroup) + { + return null; + } + + double Share(List group) => (double)group.Count(e => e.Label!.Win == true) / group.Count; + var (a, b) = (Share(inside), Share(outside)); + var all = Share([.. inside, .. outside]); + var simple = Math.Sqrt(all * (1 - all) * ((1.0 / inside.Count) + (1.0 / outside.Count))); + var months = new Dictionary<(int Year, int Month), double>(); + void Add(List group, double share, double sign) + { + foreach (var e in group) + { + var key = (e.Day.Year, e.Day.Month); + months[key] = months.GetValueOrDefault(key) + (sign * ((e.Label!.Win == true ? 1 : 0) - share) / group.Count); + } + } + + Add(inside, a, 1); + Add(outside, b, -1); + var clustered = months.Count > 1 ? Math.Sqrt(months.Values.Sum(x => x * x) * months.Count / (months.Count - 1)) : 0; + var error = Math.Max(simple, clustered); + return error > 0 ? new Comparison((a - b) / error, inside.Count, inside.Count + outside.Count, a, b) : null; + } + + private static Discovery? Sentence(Comparison c, string signals, string less, string more, string neither, int questions) + { + string Fill(string text) + { + var filled = string.Format(It, text, char.ToUpper(signals[0], It) + signals[1..], signals); + return char.ToUpper(filled[0], It) + filled[1..]; + } + + // A conclusion called solid has to survive having asked many questions; a hint says by itself how little it is worth. + var needed = c.Group >= 100 ? Quantile(0.05 / questions / c.Corrected) : c.Corrected > 1 ? Quantile(0.05 / c.Corrected) : Clear; + if (Math.Abs(c.Z) >= needed) + { + return new Discovery(Fill(c.Z < 0 ? less : more), string.Create(It, $"{c.InGroup * 100:0}% di riusciti contro il {c.Others * 100:0}% degli altri"), c.Group); + } + + return Math.Abs(c.Z) < Clear && c.Group >= 20 && c.All >= 100 ? new Discovery(Fill(neither), "Le differenze stanno tutte dentro il margine d'errore", c.All) : null; + } + + /// How many standard errors leave outside, both sides together. + internal static double Quantile(double probability) + { + var (low, high) = (0.0, 10.0); + for (var i = 0; i < 60; i++) + { + var middle = (low + high) / 2; + (low, high) = Outside(middle) > probability ? (middle, high) : (low, middle); + } + + return (low + high) / 2; + } + + private static double Outside(double z) + { + // Abramowitz and Stegun 26.2.17: the tail of the normal, good to 7 digits. + var t = 1 / (1 + (0.2316419 * z)); + var d = Math.Exp(-z * z / 2) / Math.Sqrt(2 * Math.PI); + return 2 * d * t * (0.319381530 + (t * (-0.356563782 + (t * (1.781477937 + (t * (-1.821255978 + (t * 1.330274429)))))))); + } +} + +/// Computes the discoveries and the table of the news, and keeps them for the page. +public sealed class DiscoveryDesk(Database db, IClock clock, LearningStore store) +{ + public async Task LatestAsync(CancellationToken cancellationToken) => + await store.StateAsync(DiscoverySet.Key, cancellationToken).ConfigureAwait(false) ?? new DiscoverySet(); + + public async Task RefreshAsync(CancellationToken cancellationToken) + { + var found = DiscoveryFinder.Of(await store.AllAsync(cancellationToken).ConfigureAwait(false)); + var news = await NewsAsync(cancellationToken).ConfigureAwait(false); + var set = new DiscoverySet { At = clock.UtcNow, Found = found, News = news }; + await db.WriteAsync(s => LearningStore.SaveStateAsync(s, clock, DiscoverySet.Key, set, cancellationToken), cancellationToken).ConfigureAwait(false); + } + + /// + /// The mean return after each kind of event, from the first daily close after the publication. Only informative: it + /// changes neither the importance of SPEC 10.2 nor the rules of 10.5. + /// + public async Task> NewsAsync(CancellationToken cancellationToken) + { + var rows = await db.ReadAsync(s => s.QueryAsync( + "SELECT n.id, n.published_at, n.severe, v.event_type, i.id AS instrument_id, i.asset_class FROM news_stories n JOIN news_links k ON k.story_id = n.id AND k.scope = @sc " + + "JOIN instruments i ON i.venue || ':' || i.symbol = k.target LEFT JOIN news_verdicts v ON v.id = n.verdict_id WHERE n.severe IS NOT NULL OR v.event_type IS NOT NULL", + r => (At: r.Moment("published_at"), Kind: NewsEventNames.KindOf(r.TextOrNull("event_type"), r.TextOrNull("severe")), Instrument: r.Id("instrument_id"), Class: r.Text("asset_class")), + ("sc", LinkScopes.Instrument)), cancellationToken).ConfigureAwait(false); + var store = new BarStore(db, clock); + var moves = new List<(string Kind, double One, double Five)>(); + foreach (var group in rows.Where(r => r.Kind is not null).GroupBy(r => (r.Instrument, r.Class))) + { + var first = DateOnly.FromDateTime(group.Min(r => r.At).UtcDateTime).AddDays(-1); + var bars = await store.DailyAsync(group.Key.Instrument, first, DateOnly.FromDateTime(clock.UtcNow.UtcDateTime), cancellationToken).ConfigureAwait(false); + foreach (var (at, kind, _, _) in group) + { + if (AfterNews(bars, group.Key.Class, at) is { } move) + { + moves.Add((kind!, move.One, move.Five)); + } + } + } + + return + [ + .. moves.GroupBy(m => m.Kind, StringComparer.Ordinal).Select(g => new NewsImpact(g.Key, g.Count(), g.Average(m => m.One), g.Average(m => m.Five))) + .OrderByDescending(n => n.Cases).ThenBy(n => n.Kind, StringComparer.Ordinal), + ]; + } + + /// The returns one and five closes after the first close that came after the news; null until they are there. + internal static (double One, double Five)? AfterNews(IReadOnlyList bars, string assetClass, DateTimeOffset published) + { + var start = -1; + for (var i = 0; i < bars.Count && start < 0; i++) + { + start = CloseOf(bars[i].Day, assetClass) > published ? i : start; + } + + if (start < 0 || start + 5 >= bars.Count) + { + return null; + } + + double Close(int i) => bars[i].Adjusted?.Close ?? bars[i].Close; + return Close(start) > 0 ? ((Close(start + 1) / Close(start)) - 1, (Close(start + 5) / Close(start)) - 1) : null; + } + + private static DateTimeOffset CloseOf(DateOnly day, string assetClass) + { + if (assetClass != AssetClasses.Equity) + { + return new DateTimeOffset(day.AddDays(1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + } + + var local = day.ToDateTime(new TimeOnly(16, 0)); + return new DateTimeOffset(local, Zones.NewYork.GetUtcOffset(local)); + } +} + +/// The kinds of event of the language model and of the keywords, with one name for each thing. +public static class NewsEventNames +{ + /// The kind of a story: the keywords of a serious case first, then what the language model said. + public static string? KindOf(string? eventType, string? severe) => severe switch + { + SevereKinds.Cyberattack => "security_incident", + SevereKinds.Suspension => "trading_halt", + SevereKinds.Fraud or SevereKinds.Investigation => "fraud_or_investigation", + SevereKinds.Bankruptcy => "bankruptcy", + SevereKinds.Delisting => "delisting", + _ => string.IsNullOrEmpty(eventType) ? null : eventType, + }; + + public static string Label(string kind) => kind switch + { + "network_upgrade" => "Aggiornamento della rete", + "earnings" => "Trimestrale", + "guidance" => "Previsioni della società", + "regulation" => "Nuove regole", + "security_incident" => "Attacco informatico", + "fraud_or_investigation" => "Frode o indagine", + "bankruptcy" => "Fallimento", + "trading_halt" => "Sospensione degli scambi", + "listing" => "Arrivo su un mercato", + "delisting" => "Revoca dalla quotazione", + "macro_data" => "Dato economico", + "central_bank" => "Banca centrale", + "analyst_opinion" => "Parere di un analista", + "rumor" => "Voce non confermata", + _ => "Altro", + }; +} diff --git a/src/Anubis/Trading/PaperBroker.cs b/src/Anubis/Trading/PaperBroker.cs index b6230d7..22f175c 100644 --- a/src/Anubis/Trading/PaperBroker.cs +++ b/src/Anubis/Trading/PaperBroker.cs @@ -199,16 +199,10 @@ public sealed class PaperBroker : IBrokerAccount, IDisposable 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; - } + public static decimal SlippageBp(InstrumentSpec? spec) => SlippageTable.Standard.Bp(spec); - var coin = spec.BaseCurrency ?? spec.Symbol.Split('-', '/')[0]; - return coin is "BTC" or "ETH" or "SOL" ? 5m : 15m; - } + /// The slippage in force (SPEC 11.6): the standard one until the executions of a broker say otherwise. + public Func Slippage { get; init; } = () => SlippageTable.Standard; /// 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) @@ -487,7 +481,7 @@ public sealed class PaperBroker : IBrokerAccount, IDisposable var open = (decimal)bar.Open; var high = (decimal)bar.High; var low = (decimal)bar.Low; - var slip = SlippageBp(_instruments(order.Request.Symbol)) / 10_000m; + var slip = Slippage().Bp(_instruments(order.Request.Symbol)) / 10_000m; decimal? price = order.Request.Kind switch { OrderKind.Market => open * (1m - slip), @@ -517,7 +511,7 @@ public sealed class PaperBroker : IBrokerAccount, IDisposable { var request = order.Request; var spec = _instruments(request.Symbol); - var slip = SlippageBp(spec) / 10_000m; + var slip = Slippage().Bp(spec) / 10_000m; var remaining = request.Quantity - order.Filled; var firstLook = !order.Evaluated; order.Evaluated = true; diff --git a/src/Anubis/Trading/Slippage.cs b/src/Anubis/Trading/Slippage.cs new file mode 100644 index 0000000..1426008 --- /dev/null +++ b/src/Anubis/Trading/Slippage.cs @@ -0,0 +1,59 @@ +using Anubis.Data; + +namespace Anubis.Trading; + +/// The tiers of liquidity of SPEC 7.3. +public static class SlippageTiers +{ + public const string Equity = "equity"; + + public const string Major = "crypto_major"; + + public const string Minor = "crypto_minor"; + + public static readonly IReadOnlyList All = [Equity, Major, Minor]; + + public static string Of(InstrumentSpec? spec) => spec is null ? Equity : Of(spec.AssetClass, spec.BaseCurrency, spec.Symbol); + + public static string Of(string assetClass, string? baseCurrency, string symbol) + { + ArgumentNullException.ThrowIfNull(symbol); + if (assetClass == AssetClasses.Equity) + { + return Equity; + } + + return (baseCurrency ?? symbol.Split('-', '/')[0]) is "BTC" or "ETH" or "SOL" ? Major : Minor; + } + + public static string Label(string tier) => tier switch + { + Equity => "azioni", + Major => "Bitcoin, Ethereum e Solana", + _ => "altre crypto", + }; +} + +/// The slippage the simulator and the backtest apply, in basis points by tier (SPEC 7.3, 11.6). +public sealed record SlippageTable(decimal Equity, decimal Major, decimal Minor) +{ + public static SlippageTable Standard { get; } = new(5m, 5m, 15m); + + public decimal Bp(InstrumentSpec? spec) => Of(SlippageTiers.Of(spec)); + + public decimal Of(string tier) => tier switch + { + SlippageTiers.Equity => Equity, + SlippageTiers.Major => Major, + SlippageTiers.Minor => Minor, + _ => throw new ArgumentOutOfRangeException(nameof(tier), tier, "Unknown tier"), + }; + + public SlippageTable With(string tier, decimal bp) => tier switch + { + SlippageTiers.Equity => this with { Equity = bp }, + SlippageTiers.Major => this with { Major = bp }, + SlippageTiers.Minor => this with { Minor = bp }, + _ => throw new ArgumentOutOfRangeException(nameof(tier), tier, "Unknown tier"), + }; +} diff --git a/src/Anubis/Trading/TradingService.cs b/src/Anubis/Trading/TradingService.cs index e9bcd54..a9129cc 100644 --- a/src/Anubis/Trading/TradingService.cs +++ b/src/Anubis/Trading/TradingService.cs @@ -154,6 +154,7 @@ public sealed partial class TradingService : IDisposable private readonly BarStore _bars; private readonly ConcurrentDictionary<(string Venue, string Symbol), InstrumentSpec> _specs = new(); private readonly ConcurrentDictionary _managers = new(); + private volatile SlippageTable _slippage = SlippageTable.Standard; private RiskLimits _limits = RiskLimits.Default; public TradingService(Database db, IClock clock, EventBus bus, SecretStore secrets, MarketDataService? market, FxStore fx, TradingConsent consent, Guid installationId, @@ -195,6 +196,8 @@ public sealed partial class TradingService : IDisposable Learning = Learning, }; Cycle = new Anubis.Learning.LearningCycle(db, clock, Learning, Engine.LabelDataAsync); + Costs = new Anubis.Learning.CostBook(db, clock); + Discoveries = new Anubis.Learning.DiscoveryDesk(db, clock, Learning.Store); } private volatile bool _started; @@ -220,6 +223,12 @@ public sealed partial class TradingService : IDisposable /// The nightly and weekly cycle of the model (SPEC 11.4). public Anubis.Learning.LearningCycle Cycle { get; } + /// The slippage estimates (SPEC 11.6). + public Anubis.Learning.CostBook Costs { get; } + + /// The discoveries in plain words (SPEC 11.6). + public Anubis.Learning.DiscoveryDesk Discoveries { get; } + private readonly SettingsStore? _settings; /// Learning beside the decisions (SPEC 11). @@ -337,6 +346,7 @@ public sealed partial class TradingService : IDisposable _accountsRetryAt = _clock.UtcNow + AccountRetry; await GuardAsync("patrimonio", () => PhotographAsync(cancellationToken), cancellationToken).ConfigureAwait(false); await GuardAsync("modello", () => Learning.PrepareHistoryAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + await GuardAsync("stime di costo", () => RefreshCostsAsync(cancellationToken), cancellationToken).ConfigureAwait(false); await GuardAsync("stato per la guardia", () => WriteGuardStateAsync(cancellationToken), cancellationToken).ConfigureAwait(false); await GuardAsync("chiavi per la guardia", () => SendGuardKeysAsync(alpaca, okx, cancellationToken), cancellationToken).ConfigureAwait(false); _started = true; @@ -518,6 +528,24 @@ public sealed partial class TradingService : IDisposable } } + /// The slippage in force, from the next fill of the simulator on. + public async Task RefreshCostsAsync(CancellationToken cancellationToken) => _slippage = await Costs.TableAsync(cancellationToken).ConfigureAwait(false); + + // A part of the night that fails never stops the others. + private async Task NightAsync(CancellationToken cancellationToken) + { + try + { + await Cycle.RunAsync(cancellationToken).ConfigureAwait(false); + } + finally + { + await GuardAsync("stime di costo", () => Costs.MonthAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + await GuardAsync("stime di costo", () => RefreshCostsAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + await GuardAsync("scoperte", () => Discoveries.RefreshAsync(cancellationToken), cancellationToken).ConfigureAwait(false); + } + } + /// The night of the model: once, however long the absence (SPEC 5.6), and beside the others because it is long. public static ScheduledJob ModelJob(Func run) => new("modello", "Etichette e controllo del modello", Schedule.Daily(new TimeOnly(3, 0), Zones.Rome), run) @@ -530,7 +558,7 @@ public sealed partial class TradingService : IDisposable new ScheduledJob("azioni_societarie", "Dividendi e frazionamenti nei registri", Schedule.Every(TimeSpan.FromHours(1)), CorporateActionsAsync), new ScheduledJob("rischio", "Controllo del rischio e dell'interruttore", Schedule.Every(TimeSpan.FromMinutes(1)), CheckRiskAsync), new ScheduledJob("stadi", "Retrocessioni e sola uscita delle strategie", Schedule.Every(TimeSpan.FromHours(1)), CheckStagesAsync), - ModelJob(Cycle.RunAsync), + ModelJob(NightAsync), .. Engine.Jobs(), .. _market is null ? Array.Empty() : [ @@ -891,7 +919,8 @@ public sealed partial class TradingService : IDisposable 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)); + new PaperBookStore(_db, _clock, account.AccountId)) + { Slippage = () => _slippage }; 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: diff --git a/tests/Anubis.Tests/LaboratoryScreenTests.cs b/tests/Anubis.Tests/LaboratoryScreenTests.cs index d030fb7..48be06a 100644 --- a/tests/Anubis.Tests/LaboratoryScreenTests.cs +++ b/tests/Anubis.Tests/LaboratoryScreenTests.cs @@ -68,6 +68,47 @@ public sealed class LaboratoryScreenTests StringAssert.Contains(await missing.Content.ReadAsStringAsync(), "Test non trovato."); } + /// SPEC 11.6: a lower slippage waits in the Laboratorio for the confirmation of the user. + [TestMethod] + [TestCategory(Category.Integration)] + public async Task ALowerCostIsConfirmedFromTheLaboratory() + { + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite()); + await server.SignInFirstTimeAsync(); + var db = server.Host.Services!.Db; + async Task PendingAsync(decimal bp) + { + var id = Ids.NewId(SystemClock.Instance); + await db.WriteAsync(s => s.ExecuteAsync( + "INSERT INTO cost_estimates (id, tier, status, previous_bp, bp, measured_bp, low_bp, high_bp, cases, created_at, updated_at) VALUES (@id, 'crypto_minor', 'pending', @p, @b, @b, @b, @b, 40, @now, @now)", + CancellationToken.None, ("id", id), ("p", 15m), ("b", bp), ("now", DateTimeOffset.UtcNow))); + return id; + } + + var refused = await PendingAsync(9m); + StringAssert.Contains(await server.TextAsync("/laboratorio"), "Altre crypto: da 15 punti base a 9 punti base."); + using (var no = await server.PostFormAsync("/laboratorio", $"/azioni/stime-di-costo/{refused}/rifiuta", [])) + { + Assert.AreEqual("/laboratorio#stime", ServerHarness.Location(no)); + } + + using (var late = await server.PostFormAsync("/laboratorio", $"/azioni/stime-di-costo/{refused}/conferma", [])) + { + Assert.AreEqual("/laboratorio?errore=stima#stime", ServerHarness.Location(late)); + } + + var confirmed = await PendingAsync(8m); + using (var yes = await server.PostFormAsync("/laboratorio", $"/azioni/stime-di-costo/{confirmed}/conferma", [])) + { + Assert.AreEqual("/laboratorio#stime", ServerHarness.Location(yes)); + } + + var page = await server.TextAsync("/laboratorio"); + StringAssert.Contains(page, "altre crypto 8 punti base"); + StringAssert.Contains(page, "Confermata da te"); + StringAssert.Contains(page, "Rifiutata da te"); + } + [TestMethod] [TestCategory(Category.Integration)] public async Task TheDemoRunsNoTests() diff --git a/tests/Anubis.Tests/LearningMoreTests.cs b/tests/Anubis.Tests/LearningMoreTests.cs new file mode 100644 index 0000000..8257d6c --- /dev/null +++ b/tests/Anubis.Tests/LearningMoreTests.cs @@ -0,0 +1,288 @@ +using Anubis.Backtest; +using Anubis.Core; +using Anubis.Data; +using Anubis.Learning; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Tests; + +/// The simpler things the bot learns: slippage, what news does to prices, discoveries in plain words (SPEC 11.6; issue #65). +[TestClass] +[TestCategory(Category.Integration)] +public sealed class LearningMoreTests +{ + private static readonly CancellationToken _none = CancellationToken.None; + + private static List Fills(string tier, int count, double mean, bool real, int seed = 1) + { + var gen = new Gen(seed); + return [.. Enumerable.Range(0, count).Select(i => new PaidFill(tier, mean + gen.Normal(), real, TradingRig.Start.AddHours(i)))]; + } + + /// A rise from any broker account, a fall only from real money, nothing from few cases or from noise. + [TestMethod] + [TestCategory(Category.Unit)] + public void TheRegressionRisesByItselfAndFallsOnlyOnRealMoney() + { + var table = SlippageTable.Standard; + var rise = CostRegression.Of(Fills(SlippageTiers.Major, 40, 8.2, real: false), table).Single(); + Assert.IsTrue(rise.Rise); + Assert.IsTrue(rise.Bp >= rise.Measured && rise.Bp - rise.Measured < CostRegression.Step && rise.Bp % CostRegression.Step == 0, $"{rise.Bp}"); + Assert.HasCount(0, CostRegression.Of(Fills(SlippageTiers.Major, 29, 8.2, real: true), table), "too few"); + Assert.HasCount(0, CostRegression.Of(Fills(SlippageTiers.Major, 40, 5.1, real: true), table), "noise around what is in force"); + Assert.HasCount(0, CostRegression.Of(Fills(SlippageTiers.Minor, 200, 4, real: false), table), "a fall on a practice account"); + var fall = CostRegression.Of(Fills(SlippageTiers.Minor, 40, 4, real: true), table).Single(); + Assert.IsFalse(fall.Rise); + Assert.IsTrue(fall.Bp is > 3m and < 5m); + + // Real money says less but everything together says more: the cautious side wins. + var mixed = CostRegression.Of([.. Fills(SlippageTiers.Equity, 40, 4, real: true), .. Fills(SlippageTiers.Equity, 400, 9, real: false, seed: 2)], table).Single(); + Assert.IsTrue(mixed.Rise); + + // Better than the middle price: never a negative or a zero slippage. + Assert.AreEqual(CostRegression.Step, CostRegression.Of(Fills(SlippageTiers.Equity, 60, -4, real: true), table).Single().Bp); + } + + private static async Task FillAsync(TradingRig rig, Guid account, Instrument instrument, decimal bp, int n, OrderPurpose purpose = OrderPurpose.Entry) + { + var order = Ids.NewId(rig.Clock); + await rig.Db.WriteAsync(async s => + { + await s.ExecuteAsync("INSERT INTO orders (id, account_id, instrument_id, strategy, client_order_id, side, order_type, quantity, status, created_at, updated_at, purpose) " + + "VALUES (@id, @a, @i, 'x', @c, 'buy', 'market', @q, 'filled', @now, @now, @p)", _none, ("id", order), ("a", account), ("i", instrument.Id), ("c", "O" + order), ("q", 1m), + ("now", rig.Clock.UtcNow), ("p", Wire.Text(purpose))).ConfigureAwait(false); + 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, 'buy', @q, @q, @z, 'EUR', @at, @at, 'x', @q, @bp)", _none, ("id", Ids.NewId(rig.Clock)), ("a", account), ("o", order), ("i", instrument.Id), + ("e", "E" + order), ("q", 1m), ("z", 0m), ("at", rig.Clock.UtcNow.AddDays(-1).AddMinutes(n)), ("bp", bp)).ConfigureAwait(false); + }, _none).ConfigureAwait(false); + } + + /// The month: the simulator and the stops never count, a rise is applied and said, it runs once. + [TestMethod] + public async Task TheMonthLooksOnlyAtTheExecutionsOfABroker() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var simulated = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); + var demo = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Demo, "demo").ConfigureAwait(false); + var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); + var book = new CostBook(rig.Db, rig.Clock); + for (var i = 0; i < 40; i++) + { + await FillAsync(rig, simulated.AccountId, btc, 40m, i).ConfigureAwait(false); + await FillAsync(rig, demo.AccountId, btc, 60m, i, OrderPurpose.Stop).ConfigureAwait(false); + } + + Assert.IsTrue(await book.MonthAsync(_none).ConfigureAwait(false)); + Assert.HasCount(0, await book.ListAsync(_none).ConfigureAwait(false)); + for (var i = 0; i < 40; i++) + { + await FillAsync(rig, demo.AccountId, btc, 7.2m, i).ConfigureAwait(false); + } + + Assert.IsFalse(await book.MonthAsync(_none).ConfigureAwait(false), "once for each month"); + rig.Clock.Advance(TimeSpan.FromDays(31)); + Assert.IsTrue(await book.MonthAsync(_none).ConfigureAwait(false)); + var row = (await book.ListAsync(_none).ConfigureAwait(false)).Single(); + Assert.AreEqual((SlippageTiers.Major, CostStatuses.Applied, 5m, 7.5m, 40), (row.Tier, row.Status, row.PreviousBp, row.Bp, row.Cases)); + Assert.AreEqual(SlippageTable.Standard with { Major = 7.5m }, await book.TableAsync(_none).ConfigureAwait(false)); + Assert.AreEqual("Scostamento misurato su 40 esecuzioni (Bitcoin, Ethereum e Solana): 7,2 punti base invece dei 5,0 previsti. Da ora simulatore e backtest ne contano 7,5.", + (await NewsRulesTests.DiaryAsync(rig.Db).ConfigureAwait(false))[^1]); + + // The next month the estimate in force is the new one: nothing to say. + rig.Clock.Advance(TimeSpan.FromDays(31)); + Assert.IsTrue(await book.MonthAsync(_none).ConfigureAwait(false)); + Assert.HasCount(1, await book.ListAsync(_none).ConfigureAwait(false)); + } + + /// A fall changes nothing until the user confirms it; refused, or grown old, it never will. + [TestMethod] + public async Task AFallWaitsForTheUser() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var live = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Live).ConfigureAwait(false); + var pepe = await rig.InstrumentAsync(TradingRig.Pepe).ConfigureAwait(false); + for (var i = 0; i < 40; i++) + { + await FillAsync(rig, live.AccountId, pepe, 6m, i).ConfigureAwait(false); + } + + var book = new CostBook(rig.Db, rig.Clock); + await book.MonthAsync(_none).ConfigureAwait(false); + var first = (await book.ListAsync(_none).ConfigureAwait(false)).Single(); + Assert.AreEqual((CostStatuses.Pending, 6m), (first.Status, first.Bp)); + Assert.AreEqual(SlippageTable.Standard, await book.TableAsync(_none).ConfigureAwait(false)); + Assert.HasCount(1, await rig.QueryAsync("SELECT id FROM notifications WHERE kind = 'cost_pending'", r => r.Id("id")).ConfigureAwait(false)); + + // A month later the same proposal takes its place; the old one cannot be confirmed any more. + rig.Clock.Advance(TimeSpan.FromDays(31)); + await book.MonthAsync(_none).ConfigureAwait(false); + Assert.IsFalse(await book.DecideAsync(first.Id, true, "utente", _none).ConfigureAwait(false)); + var second = (await book.ListAsync(_none).ConfigureAwait(false)).Single(e => e.Status == CostStatuses.Pending); + Assert.IsTrue(await book.DecideAsync(second.Id, false, "utente", _none).ConfigureAwait(false)); + Assert.AreEqual(SlippageTable.Standard, await book.TableAsync(_none).ConfigureAwait(false)); + + rig.Clock.Advance(TimeSpan.FromDays(31)); + await book.MonthAsync(_none).ConfigureAwait(false); + var third = (await book.ListAsync(_none).ConfigureAwait(false)).Single(e => e.Status == CostStatuses.Pending); + Assert.IsTrue(await book.DecideAsync(third.Id, true, "utente", _none).ConfigureAwait(false)); + Assert.IsFalse(await book.DecideAsync(third.Id, false, "utente", _none).ConfigureAwait(false), "only once"); + Assert.AreEqual(SlippageTable.Standard with { Minor = 6m }, await book.TableAsync(_none).ConfigureAwait(false)); + Assert.AreEqual("utente", (await book.ListAsync(_none).ConfigureAwait(false))[^1].DecidedBy); + } + + /// The table in force reaches the simulator and the plan of a backtest, where it stays written. + [TestMethod] + public async Task TheEstimatesReachTheSimulatorAndThePlanOfATest() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false); + await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); + var table = SlippageTable.Standard; + using var paper = new PaperBroker(PaperOptions.Okx() with { MinLatency = TimeSpan.Zero, MaxLatency = TimeSpan.Zero }, rig.Clock, rig.QuoteAsync, rig.Spec) { Slippage = () => table }; + await paper.DepositAsync(10000m, "EUR", _none).ConfigureAwait(false); + rig.Quote("BTC-EUR", 60000m, 60000m); + async Task BuyAsync(string id) + { + await paper.SubmitOrderAsync(new OrderRequest(id, "BTC-EUR", OrderSide.Buy, OrderKind.Market, 0.01m, TimeInForce.Ioc), _none).ConfigureAwait(false); + await paper.PumpAsync(_none).ConfigureAwait(false); + return (await paper.GetFillsAsync(TradingRig.Start, _none).ConfigureAwait(false)).Single(f => f.ClientOrderId == id).Price; + } + + Assert.AreEqual(60030m, await BuyAsync("B1").ConfigureAwait(false)); + table = table with { Major = 20m }; + Assert.AreEqual(60120m, await BuyAsync("B2").ConfigureAwait(false)); + + Assert.AreEqual(60030m, CostModel.Standard.ExecutionPrice(TradingRig.Btc, OrderSide.Buy, 60000m)); + Assert.AreEqual(60240m, new CostModel(2m) { Slippage = table }.ExecutionPrice(TradingRig.Btc, OrderSide.Buy, 60000m)); + var request = new TrialRequest(StrategyCatalog.All[0].Id, TrialSources.Research, Venues.Binance, ["BTCEUR"], new DateOnly(2024, 1, 1), new DateOnly(2025, 1, 1), 1000m, null); + var plain = Laboratory.BuildPlan(request, rig.Clock.UtcNow, SlippageTable.Standard).Plan; + Assert.AreEqual(Laboratory.BuildPlan(request, rig.Clock.UtcNow).Plan.ToJson(), plain.ToJson(), "the plans written so far stay what they are"); + var plan = Laboratory.BuildPlan(request, rig.Clock.UtcNow, table).Plan; + Assert.AreEqual(table, TrialPlan.FromJson(plan.ToJson()).Slippage); + Assert.AreNotEqual(TrialPlan.Hash(plain.ToJson()), TrialPlan.Hash(plan.ToJson())); + } + + /// The mean return after each kind of event, from the first close after the publication. + [TestMethod] + public async Task TheTableOfTheNewsStartsFromTheFirstCloseAfter() + { + await using var rig = await TradingRig.CreateAsync().ConfigureAwait(false); + var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false); + var first = new DateOnly(2026, 1, 1); + await new BarStore(rig.Db, rig.Clock).UpsertDailyAsync(btc.Id, Enumerable.Range(0, 20).Select(i => + { + var close = i switch { < 4 => 100.0, 4 => 90, 5 => 81, _ => 45 }; + return new DailyBar(first.AddDays(i), close, close, close, close, 1); + }), "test", _none).ConfigureAwait(false); + + // Published during the fourth day (close 100): then 90 the day after, 45 five days after. + await NewsRulesTests.StoryAsync(rig.Db, rig.Clock, btc.Spec, "Exchange hacked", new DateTimeOffset(2026, 1, 4, 10, 0, 0, TimeSpan.Zero), 4, -0.9, "A", trusted: true).ConfigureAwait(false); + + // Published when the fifth had already closed: the first close after is 81, then 45 and 45. + await NewsRulesTests.StoryAsync(rig.Db, rig.Clock, btc.Spec, "Bridge hacked", new DateTimeOffset(2026, 1, 6, 0, 0, 0, TimeSpan.Zero), 4, -0.9, "A", trusted: true).ConfigureAwait(false); + + // Too recent, and of no known kind: they do not count. + await NewsRulesTests.StoryAsync(rig.Db, rig.Clock, btc.Spec, "Wallet hacked", new DateTimeOffset(2026, 1, 18, 0, 0, 0, TimeSpan.Zero), 4, -0.9, "A", trusted: true).ConfigureAwait(false); + await NewsRulesTests.StoryAsync(rig.Db, rig.Clock, btc.Spec, "Bitcoin quiet", new DateTimeOffset(2026, 1, 2, 0, 0, 0, TimeSpan.Zero), 2, 0.1, "A", trusted: true).ConfigureAwait(false); + var desk = new DiscoveryDesk(rig.Db, rig.Clock, new LearningStore(rig.Db, rig.Clock)); + await desk.RefreshAsync(_none).ConfigureAwait(false); + var impact = (await desk.LatestAsync(_none).ConfigureAwait(false)).News.Single(); + Assert.AreEqual(("security_incident", 2, "troppo pochi per fidarsi"), (impact.Kind, impact.Cases, impact.Trust)); + Assert.AreEqual((-0.1 + ((45.0 / 81) - 1)) / 2, impact.OneDay, 1e-9); + Assert.AreEqual((-0.55 + ((45.0 / 81) - 1)) / 2, impact.FiveDays, 1e-9); + Assert.AreEqual("Attacco informatico", NewsEventNames.Label(impact.Kind)); + foreach (var kind in News.NewsVerdicts.EventTypes.Where(k => k != "other")) + { + Assert.AreNotEqual("Altro", NewsEventNames.Label(kind), kind); + } + } + + /// The close of a stock is at four in New York, not at midnight. + [TestMethod] + [TestCategory(Category.Unit)] + public void TheCloseOfAStockIsInNewYork() + { + var bars = Enumerable.Range(0, 8).Select(i => new DailyBar(new DateOnly(2026, 7, 1).AddDays(i), 1, 1, 1, 100 + i, 1)).ToList(); + var before = DiscoveryDesk.AfterNews(bars, AssetClasses.Equity, new DateTimeOffset(2026, 7, 1, 19, 59, 0, TimeSpan.Zero)); + var after = DiscoveryDesk.AfterNews(bars, AssetClasses.Equity, new DateTimeOffset(2026, 7, 1, 20, 0, 0, TimeSpan.Zero)); + Assert.AreEqual(0.01, before!.Value.One, 1e-9); + Assert.AreEqual(1.0 / 101, after!.Value.One, 1e-9); + } + + private static IReadOnlyList Examples(int count, Func make, int perDay = 1) + { + var gen = new Gen(4); + return + [ + .. Enumerable.Range(0, count).Select(i => + { + var (volatility, win) = make(i, gen); + var day = new DateOnly(2021, 1, 1).AddDays(i / perDay * 3); + return new Example(Guid.NewGuid(), StrategyNames.CryptoTrend, "C" + i, CaseSources.Live, day, new DateTimeOffset(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), "t", 0.1m, null, null, + new Dictionary { [Clues.VolatilityRatio] = volatility }) + { Label = new CaseLabel(win, win ? 0.1 : -0.1, day, day.AddDays(1), "x") }; + }), + ]; + } + + /// A real relation is found and said with its cases; without one, the bot says that it does not matter. + [TestMethod] + [TestCategory(Category.Unit)] + public void ARelationIsSaidWithItsCasesAndItsTrust() + { + var real = DiscoveryFinder.Of(Examples(900, (i, gen) => i % 3 == 0 ? (2, gen.Double() < 0.25) : (1, gen.Double() < 0.55))); + var found = real[0]; + Assert.AreEqual("I segnali di trend sulle crypto riescono meno quando i prezzi sono molto più agitati del solito", found.Title); + Assert.AreEqual((300, "conclusione solida"), (found.Cases, found.Trust)); + Assert.MatchesRegex(new System.Text.RegularExpressions.Regex("^[0-9]+% di riusciti contro il [0-9]+% degli altri$"), found.Detail); + + var hint = DiscoveryFinder.Of(Examples(200, (i, gen) => i % 5 == 0 ? (2, gen.Double() < 0.1) : (1, gen.Double() < 0.6))); + Assert.AreEqual((40, "un indizio discreto"), (hint[0].Cases, hint[0].Trust)); + + var nothing = DiscoveryFinder.Of(Examples(900, (i, gen) => (i % 3 == 0 ? 2 : 1, gen.Double() < 0.4))); + Assert.IsTrue(nothing.Any(d => d.Title == "Il giorno della settimana non conta per i segnali di trend sulle crypto" && d.Cases == 900)); + Assert.IsTrue(nothing.All(d => d.Detail == "Le differenze stanno tutte dentro il margine d'errore"), string.Join('|', nothing.Select(d => d.Title))); + + // Too few to say anything at all. + Assert.HasCount(0, DiscoveryFinder.Of(Examples(15, (i, gen) => (i % 2 == 0 ? 2 : 1, i % 2 == 0)))); + Assert.AreEqual("troppo pochi per fidarsi", Discovery.TrustOf(19)); + Assert.AreEqual("un indizio discreto", Discovery.TrustOf(99)); + } + + /// On pure chance almost nothing is declared: the many questions and the coins that move together are counted. + [TestMethod] + [TestCategory(Category.Unit)] + public void ChanceIsNotADiscovery() + { + var declared = 0; + for (var seed = 0; seed < 60; seed++) + { + var gen = new Gen(seed); + var months = new Dictionary(); + + // Whole months win or lose together, and whole months are agitated or calm, with no relation between the two. + var examples = Examples(1200, (i, _) => + { + var month = i / 60; + if (!months.TryGetValue(month, out var m)) + { + months[month] = m = (gen.Bool(), gen.Bool() ? 0.2 : 0.6); + } + + return (m.High ? 2 : 1, gen.Double() < m.Chance); + }, perDay: 6); + declared += DiscoveryFinder.Of(examples).Any(d => d.Detail.Contains("contro", StringComparison.Ordinal)) ? 1 : 0; + } + + Assert.IsLessThanOrEqualTo(6, declared, $"{declared} of 60"); + } + + [TestMethod] + [TestCategory(Category.Unit)] + public void TheQuantileIsTheOneOfTheNormal() + { + Assert.AreEqual(1.959964, DiscoveryFinder.Quantile(0.05), 1e-4); + Assert.AreEqual(2.575829, DiscoveryFinder.Quantile(0.01), 1e-4); + } +}