Learn slippage from real executions and say discoveries in plain words
The monthly regression raises an estimate by itself and lowers one only on real money and with the confirmation of the user in the Laboratorio. The table of what news does to prices and the fixed list of questions on the clues are informative only. refs #65 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
df21962da3
commit
14e8a872dc
15 files changed
+1060
-22
No files matched your search
@@ -5,7 +5,9 @@
|
||||
@inject IClock Clock
|
||||
@using Anubis.Backtest
|
||||
@using Anubis.Data
|
||||
@using Anubis.Learning
|
||||
@using Anubis.Strategies
|
||||
@using Anubis.Trading
|
||||
|
||||
<PageTitle>Laboratorio · Anubis</PageTitle>
|
||||
|
||||
@@ -173,10 +175,47 @@
|
||||
|
||||
<section class="panel" aria-labelledby="stime">
|
||||
<h2 id="stime">Stime di costo da confermare</h2>
|
||||
<div class="empty">
|
||||
<p class="empty-title">Nessuna stima da confermare.</p>
|
||||
<p>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.</p>
|
||||
</div>
|
||||
<p class="hint">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.</p>
|
||||
@if (_costs.Where(c => c.Status == CostStatuses.Pending).ToList() is { Count: > 0 } pending)
|
||||
{
|
||||
@foreach (var c in pending)
|
||||
{
|
||||
<div class="row">
|
||||
<p>@Capital(SlippageTiers.Label(c.Tier)): da @Bp(c.PreviousBp) a @Bp(c.Bp). <span class="note">Misurati @Bp(c.MeasuredBp) su @c.Cases esecuzioni con soldi veri (tra @Bp(c.LowBp) e @Bp(c.HighBp) al 95%).</span></p>
|
||||
<form method="post" action="/azioni/stime-di-costo/@c.Id/conferma" class="form-inline"><AntiforgeryToken /><button class="btn btn-small" type="submit" data-confirm="Simulatore e backtest conteranno costi più bassi. Confermi?">Conferma</button></form>
|
||||
<form method="post" action="/azioni/stime-di-costo/@c.Id/rifiuta" class="form-inline"><AntiforgeryToken /><button class="btn btn-small" type="submit">Rifiuta</button></form>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="empty">
|
||||
<p class="empty-title">Nessuna stima da confermare.</p>
|
||||
<p>Quando le esecuzioni con soldi veri diranno che lo scostamento è più basso di quello previsto, la nuova stima aspetterà qui la tua conferma.</p>
|
||||
</div>
|
||||
}
|
||||
@if (_costs.Where(c => c.Status != CostStatuses.Pending).Reverse().Take(10).ToList() is { Count: > 0 } past)
|
||||
{
|
||||
<div class="table-wrap">
|
||||
<table class="table">
|
||||
<caption class="sr-only">Stime di scostamento già decise</caption>
|
||||
<thead><tr><th scope="col">Quando</th><th scope="col">Strumenti</th><th scope="col" class="num">Prima</th><th scope="col" class="num">Stima</th><th scope="col" class="num">Esecuzioni</th><th scope="col">Esito</th></tr></thead>
|
||||
<tbody>
|
||||
@foreach (var c in past)
|
||||
{
|
||||
<tr>
|
||||
<td class="nowrap">@Format.ShortDate(c.DecidedAt ?? c.CreatedAt, Shell.Now, Shell.Zone)</td>
|
||||
<td>@Capital(SlippageTiers.Label(c.Tier))</td>
|
||||
<td class="num">@Bp(c.PreviousBp)</td>
|
||||
<td class="num">@Bp(c.Bp)</td>
|
||||
<td class="num">@c.Cases</td>
|
||||
<td>@Outcome(c.Status)</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
@code {
|
||||
@@ -188,6 +227,8 @@
|
||||
private DateOnly _from;
|
||||
private DateOnly _to;
|
||||
private IReadOnlyList<string> _research = [];
|
||||
private IReadOnlyList<CostEstimate> _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) + ".";
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A lower slippage estimate waits for the user (SPEC 11.6).</summary>
|
||||
private static async Task<IResult> 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;
|
||||
|
||||
|
||||
@@ -20,6 +20,9 @@ public sealed record CostModel(decimal Multiplier = 1m)
|
||||
{
|
||||
public static CostModel Standard { get; } = new();
|
||||
|
||||
/// <summary>The slippage in force when the test was planned (SPEC 11.6).</summary>
|
||||
public SlippageTable Slippage { get; init; } = SlippageTable.Standard;
|
||||
|
||||
/// <summary>The price list of the venue where the instrument would trade. Research archives trade like OKX.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>The price paid or received: the reference moved by the slippage, rounded to the tick against us.</summary>
|
||||
public decimal ExecutionPrice(InstrumentSpec spec, OrderSide side, decimal reference)
|
||||
|
||||
@@ -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
|
||||
/// <summary>Checks the request, writes the plan and queues the trial. The plan is final from here on.</summary>
|
||||
public async Task<Trial> 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;
|
||||
}
|
||||
|
||||
/// <summary>The plan of a request: the family's own grid where the request gives none, the default costs, checks and thresholds.</summary>
|
||||
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)
|
||||
|
||||
@@ -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<ReportCosts>();
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
/// </summary>
|
||||
public decimal? ReferenceShare { get; init; }
|
||||
|
||||
/// <summary>The slippage in force when the plan was written (SPEC 11.6); null for the standard one.</summary>
|
||||
public SlippageTable? Slippage { get; init; }
|
||||
|
||||
public static readonly JsonSerializerOptions Json = new()
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
|
||||
|
||||
@@ -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);
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>In force since it was made: a rise.</summary>
|
||||
public const string Applied = "applied";
|
||||
|
||||
/// <summary>A fall that waits for the user.</summary>
|
||||
public const string Pending = "pending";
|
||||
|
||||
/// <summary>A fall in force because the user confirmed it.</summary>
|
||||
public const string Confirmed = "confirmed";
|
||||
|
||||
public const string Refused = "refused";
|
||||
|
||||
/// <summary>A proposal that a later month replaced before the user decided.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>An execution obtained from a broker: never the internal simulator, which would give back its own guess.</summary>
|
||||
public sealed record PaidFill(string Tier, double SlippageBp, bool RealMoney, DateTimeOffset At);
|
||||
|
||||
/// <summary>What the executions of a tier propose.</summary>
|
||||
public sealed record CostProposal(string Tier, bool Rise, decimal Bp, decimal Measured, decimal Low, decimal High, int Cases);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class CostRegression
|
||||
{
|
||||
/// <summary>Fewer executions than this in a tier say nothing.</summary>
|
||||
public const int MinCases = 30;
|
||||
|
||||
/// <summary>The estimates move by half basis points, always up to the next: cautious.</summary>
|
||||
public const decimal Step = 0.5m;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<CostProposal> Of(IReadOnlyList<PaidFill> fills, SlippageTable table)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(fills);
|
||||
ArgumentNullException.ThrowIfNull(table);
|
||||
var proposals = new List<CostProposal>();
|
||||
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<PaidFill> 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);
|
||||
}
|
||||
|
||||
/// <summary>The slippage estimates: the table in force, the monthly run, what waits for the user (SPEC 11.6).</summary>
|
||||
public sealed class CostBook(Database db, IClock clock)
|
||||
{
|
||||
public const string StateKey = "cost_month";
|
||||
|
||||
/// <summary>How far back the executions count.</summary>
|
||||
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<SlippageTable> TableAsync(CancellationToken cancellationToken) =>
|
||||
TableOf(await ListAsync(cancellationToken).ConfigureAwait(false));
|
||||
|
||||
/// <summary>Every estimate, oldest first.</summary>
|
||||
public Task<List<CostEstimate>> ListAsync(CancellationToken cancellationToken) => db.ReadAsync(ListAsync, cancellationToken);
|
||||
|
||||
private static Task<List<CostEstimate>> 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<CostEstimate> 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;
|
||||
}
|
||||
|
||||
/// <summary>The run of the month: once for each month, at the first night it finds. True when it ran.</summary>
|
||||
public async Task<bool> 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<Month>(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);
|
||||
}
|
||||
|
||||
/// <summary>The user confirms or refuses a fall. False when it is not waiting any more, or it would not be a fall now.</summary>
|
||||
public Task<bool> 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);
|
||||
|
||||
/// <summary>
|
||||
/// The executions obtained from a broker since <paramref name="since"/>. A stop that jumped a gap is not slippage: the
|
||||
/// simulator and the backtest already fill it at the price after the gap.
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<PaidFill>> 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)),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>A relation in plain Italian, with what supports it (SPEC 11.6).</summary>
|
||||
public sealed record Discovery(string Title, string Detail, int Cases)
|
||||
{
|
||||
/// <summary>The judgement on the number of cases, with the words of SPEC 11.6.</summary>
|
||||
public string Trust => TrustOf(Cases);
|
||||
|
||||
public static string TrustOf(int cases) => cases < 20 ? "troppo pochi per fidarsi" : cases < 100 ? "un indizio discreto" : "conclusione solida";
|
||||
}
|
||||
|
||||
/// <summary>What happened to the prices after the news of a kind: the mean return one and five closes later.</summary>
|
||||
public sealed record NewsImpact(string Kind, int Cases, double OneDay, double FiveDays)
|
||||
{
|
||||
public string Trust => Discovery.TrustOf(Cases);
|
||||
}
|
||||
|
||||
/// <summary>The discoveries as they were last computed.</summary>
|
||||
public sealed record DiscoverySet
|
||||
{
|
||||
public const string Key = "discoveries";
|
||||
|
||||
public DateTimeOffset At { get; init; }
|
||||
|
||||
public IReadOnlyList<Discovery> Found { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<NewsImpact> News { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class DiscoveryFinder
|
||||
{
|
||||
/// <summary>A group smaller than this is not worth a sentence.</summary>
|
||||
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");
|
||||
|
||||
/// <summary>A question: the examples in which the condition held against all the others of the strategy.</summary>
|
||||
private sealed record Question(string Clue, Func<double, bool> Holds, string Less, string More, string Neither);
|
||||
|
||||
private static readonly IReadOnlyList<Question> 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",
|
||||
};
|
||||
|
||||
/// <summary>The relations that hold, and those that surely do not, the clearest first.</summary>
|
||||
public static IReadOnlyList<Discovery> Of(IReadOnlyList<Example> examples)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(examples);
|
||||
var answers = new List<(double Z, int Group, Func<int, Discovery?> 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)
|
||||
{
|
||||
/// <summary>How many comparisons hide behind this one.</summary>
|
||||
public int Corrected { get; init; } = 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static Comparison? Compare(IReadOnlyList<Example> examples, Func<Example, bool> 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<Example> 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<Example> 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;
|
||||
}
|
||||
|
||||
/// <summary>How many standard errors leave <paramref name="probability"/> outside, both sides together.</summary>
|
||||
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))))))));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Computes the discoveries and the table of the news, and keeps them for the page.</summary>
|
||||
public sealed class DiscoveryDesk(Database db, IClock clock, LearningStore store)
|
||||
{
|
||||
public async Task<DiscoverySet> LatestAsync(CancellationToken cancellationToken) =>
|
||||
await store.StateAsync<DiscoverySet>(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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<NewsImpact>> 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),
|
||||
];
|
||||
}
|
||||
|
||||
/// <summary>The returns one and five closes after the first close that came after the news; null until they are there.</summary>
|
||||
internal static (double One, double Five)? AfterNews(IReadOnlyList<DailyBar> 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));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The kinds of event of the language model and of the keywords, with one name for each thing.</summary>
|
||||
public static class NewsEventNames
|
||||
{
|
||||
/// <summary>The kind of a story: the keywords of a serious case first, then what the language model said.</summary>
|
||||
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",
|
||||
};
|
||||
}
|
||||
@@ -199,16 +199,10 @@ public sealed class PaperBroker : IBrokerAccount, IDisposable
|
||||
public PaperOptions Options => _options;
|
||||
|
||||
/// <summary>Slippage by liquidity tier (SPEC 7.3): 5 bp for stocks and BTC, ETH, SOL; 15 bp for other coins.</summary>
|
||||
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;
|
||||
}
|
||||
/// <summary>The slippage in force (SPEC 11.6): the standard one until the executions of a broker say otherwise.</summary>
|
||||
public Func<SlippageTable> Slippage { get; init; } = () => SlippageTable.Standard;
|
||||
|
||||
/// <summary>Puts money on the simulated account: the bot's capital lives in its ledger, this is only the balance.</summary>
|
||||
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;
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
using Anubis.Data;
|
||||
|
||||
namespace Anubis.Trading;
|
||||
|
||||
/// <summary>The tiers of liquidity of SPEC 7.3.</summary>
|
||||
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<string> 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",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The slippage the simulator and the backtest apply, in basis points by tier (SPEC 7.3, 11.6).</summary>
|
||||
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"),
|
||||
};
|
||||
}
|
||||
@@ -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<Guid, OrderManager> _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
|
||||
/// <summary>The nightly and weekly cycle of the model (SPEC 11.4).</summary>
|
||||
public Anubis.Learning.LearningCycle Cycle { get; }
|
||||
|
||||
/// <summary>The slippage estimates (SPEC 11.6).</summary>
|
||||
public Anubis.Learning.CostBook Costs { get; }
|
||||
|
||||
/// <summary>The discoveries in plain words (SPEC 11.6).</summary>
|
||||
public Anubis.Learning.DiscoveryDesk Discoveries { get; }
|
||||
|
||||
private readonly SettingsStore? _settings;
|
||||
|
||||
/// <summary>Learning beside the decisions (SPEC 11).</summary>
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The slippage in force, from the next fill of the simulator on.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The night of the model: once, however long the absence (SPEC 5.6), and beside the others because it is long.</summary>
|
||||
public static ScheduledJob ModelJob(Func<CancellationToken, Task> 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<ScheduledJob>() :
|
||||
[
|
||||
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user