Files
Anubis/src/Anubis.Server/Components/Pages/Conti.razor
T
Alby96andClaude Opus 5.5 d97304d7b9 Add the event-driven backtest engine and the strategy interface (refs #34)
The strategy contract of SPEC 5.3 (IStrategy, StrategyContext, Intent) is
shared by backtest and live: the context exposes bars only up to the
decision, adjusted and anchored to that day, and reading past it throws.
The engine runs each session as ordered events (corporate actions, open,
session, close), decides on the close and executes at the next open with
the simulator's price lists, slippage tiers, tick and lot rounding,
minimums and no leverage. Corrective and risk hooks are wired in and pass
everything through until Phase 5. One decision cycle can restart from a
recorded book (SPEC 12.3).

A scripted toy strategy reproduces a result computed by hand to the cent
on OKX and Alpaca costs. The Phase 3 class Trading.Strategies becomes
StrategyNames so the Anubis.Strategies namespace can exist.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 09:29:01 +01:00

415 lines
23 KiB
Plaintext

@inherits LoadedComponent
@page "/conti"
@inject AnubisHost Host
@inject ShellData Shell
@inject IClock Clock
@using Anubis.Trading
@using Anubis.Data
<PageTitle>Conti e posizioni · Anubis</PageTitle>
@{
var v = _view;
var c = _currency;
}
@if (!v.HasAccounts)
{
<Pending Title="Nessun conto ancora.">Il bot crea da solo i due simulatori interni, OKX e Alpaca, al primo avvio del motore di trading. I conti di prova dei broker compaiono quando ne aggiungi le chiavi in <a href="/impostazioni#conti">Impostazioni</a>.</Pending>
}
else
{
@if (_message is { } message)
{
<p class="notice @(_ok ? "notice-gain" : "notice-loss")" role="status"><Icon Name="@(_ok ? "check" : "alert")" Size="16" />@message</p>
}
var shares = Format.Shares([.. v.Slices.Select(s => s.Eur), v.CashEur]);
var winners = v.Positions.Count(p => p.ResultEur >= 0);
<section class="panel totals" aria-label="Totale dei conti">
<div class="totals-cells">
<div class="cell">
<span class="cell-label">Totale dei conti</span>
<span class="total-value">@Shell.Money(v.TotalEur, c)</span>
<span class="cell-change @(v.ResultEur >= 0 ? "gain" : "loss")"><Arrow Up="v.ResultEur >= 0" />@Shell.Money(v.ResultEur, c, withSign: true) dall'avvio</span>
</div>
<div class="cell">
<span class="cell-label">Investito</span>
<span class="total-value">@Shell.Money(v.InvestedEur, c)</span>
<span class="cell-note">@Format.Percent(Part(v.InvestedEur, v.TotalEur)) del totale</span>
</div>
<div class="cell">
<span class="cell-label">Liquidità</span>
<span class="total-value">@Shell.Money(v.CashEur, c)</span>
<span class="cell-note">@Format.Percent(Part(v.CashEur, v.TotalEur)) del totale</span>
</div>
<div class="cell">
<span class="cell-label">Risultato delle posizioni aperte</span>
<span class="total-value">@Shell.Money(v.OpenResultEur, c, withSign: true)</span>
<span class="cell-note">@(v.Positions.Count == 0 ? "Nessuna posizione aperta" : $"{winners} in guadagno, {v.Positions.Count - winners} in perdita")</span>
</div>
</div>
<div class="split-bar" role="img" aria-label="Divisione del totale tra strategie e liquidità">
@for (var i = 0; i < v.Slices.Count; i++)
{
if (shares[i] > 0)
{
<span style="width: @Css(shares[i])%; background: @v.Slices[i].Color"></span>
}
}
@if (shares[^1] > 0)
{
<span style="width: @Css(shares[^1])%; background: var(--cash)"></span>
}
</div>
<ul class="split-legend">
@for (var i = 0; i < v.Slices.Count; i++)
{
<li><span class="swatch" style="background: @v.Slices[i].Color"></span>@v.Slices[i].Label <strong>@Format.Percent(shares[i])</strong></li>
}
<li><span class="swatch" style="background: var(--cash)"></span>Liquidità <strong>@Format.Percent(shares[^1])</strong></li>
</ul>
</section>
<div class="account-grid">
@foreach (var a in v.Accounts)
{
var state = a.State;
var up = a.Result >= 0;
var usd = a.Currency == "USD";
<section class="panel account" aria-label="@a.Name">
<div class="account-head">
<h2>@a.Name <span class="tag">@a.Kind</span></h2>
<span class="link-state @(state.LastOutcome == ReconcileOutcomes.Unreachable ? "down" : null)"><span class="dot"></span>@Connection(a)</span>
</div>
<div class="account-value">
<span class="account-equity">@Shell.Money(a.Eur(a.Equity), c)</span>
@if (usd)
{
<span class="account-native">@Format.Money(a.Equity, "USD")</span>
}
<span class="cell-change @(up ? "gain" : "loss")"><Arrow Up="up" />@Shell.Money(a.Eur(a.Result), c, withSign: true) (@Format.Percent(a.Percent, 2, withSign: true))</span>
</div>
<dl class="account-lines">
<dt>Liquidità in @(usd ? "dollari" : "euro")</dt>
<dd><strong>@Shell.Money(a.Eur(a.Cash), c)</strong>@if (usd) {<span class="native"> @Format.Money(a.Cash, "USD")</span>}</dd>
<dt>Investito in @Holdings(a)</dt>
<dd><strong>@Shell.Money(a.InvestedEur, c)</strong>@if (usd) {<span class="native"> @Format.Money(a.Invested, "USD")</span>}</dd>
<dt>Guadagni già incassati</dt>
<dd><strong>@Shell.Money(a.Eur(a.Realized), c, withSign: true)</strong></dd>
<dt>Guadagni sulle posizioni aperte</dt>
<dd><strong>@Shell.Money(a.Eur(a.Unrealized), c, withSign: true)</strong></dd>
<dt>Commissioni pagate</dt>
<dd><strong>@Shell.Money(a.Eur(a.Fees), c)</strong></dd>
</dl>
@if (state.IsPrudent)
{
<div class="notice notice-attention prudent">
<Icon Name="alert" Size="16" />
<div>
@if (state.ModeReason == Reconciler.KeyReason)
{
<p>La chiave di questo conto permette i prelievi: niente nuovi acquisti finché non la sostituisci con una senza prelievo in <a href="/impostazioni#conti">Impostazioni</a>. Vendite e stop proseguono.</p>
}
else
{
<p>Modalità prudente dalle @Time(state.ModeSince): niente nuovi acquisti, vendite e stop proseguono.</p>
<ul class="differences">
@foreach (var d in state.Differences)
{
<li>@d.Message</li>
}
</ul>
@if (state.WaitsForUser(Clock.UtcNow, TimeSpan.FromMinutes(15)) && !Shell.IsDemo)
{
<p>Sono passati 15 minuti e la differenza non si è spiegata da sola. Scegli tu:</p>
<div class="choices">
<form method="post" action="/azioni/conti/@a.Id/allinea"><AntiforgeryToken /><button class="btn btn-small" type="submit" data-confirm="Il registro prende i numeri del conto, con una riga di rettifica che resta nel diario. Confermi?">Allinea il registro al conto</button></form>
<form method="post" action="/azioni/conti/@a.Id/escludi"><AntiforgeryToken /><button class="btn btn-small" type="submit">Lascia fuori ciò che non è del bot</button></form>
</div>
}
else
{
<p class="note">Se entro 15 minuti si spiega da sola il conto torna normale; altrimenti qui potrai scegliere se allineare il registro o lasciare fuori la differenza.</p>
}
}
</div>
</div>
}
<ul class="account-facts">
@if (a.Environment == TradingEnvironments.Simulation)
{
<li><Icon Name="flask" Size="16" />Simulazione interna: prezzi veri, ordini finti</li>
}
else
{
<li><Icon Name="flask" Size="16" />Conto di prova del broker: ordini veri su denaro finto</li>
}
@if (state.KeyCanWithdraw == true)
{
<li class="loss"><Icon Name="alert" Size="16" />La chiave permette i prelievi: va sostituita</li>
}
else if (state.KeyCheckedAt is not null)
{
<li><Icon Name="check" Size="16" />La chiave può solo leggere e fare ordini: i prelievi sono disattivati</li>
}
@if (usd)
{
<li><Icon Name="clock" Size="16" />@(v.MarketOpen ? $"Mercato aperto: chiude alle {Time(v.MarketNext)}." : $"Mercato chiuso: apre alle {Time(v.MarketNext)}.") @RateText(v, withSource: false)</li>
}
@if (state.LastReconciledAt is null)
{
<li><Icon Name="clock" Size="16" />Primo controllo con il registro entro 5 minuti</li>
}
else if (state.LastOutcome is ReconcileOutcomes.Different)
{
<li class="attention"><Icon Name="alert" Size="16" />Differenza tra conto e registro (controllo delle @Time(state.LastReconciledAt))</li>
}
else if (state.LastOutcome is ReconcileOutcomes.Unreachable)
{
<li class="attention"><Icon Name="alert" Size="16" />Il broker non risponde: riprovo ogni 5 minuti (ultimo tentativo alle @Time(state.LastReconciledAt))</li>
}
else
{
<li><Icon Name="check" Size="16" />@(a.Environment == TradingEnvironments.Simulation ? "Registro interno coerente" : "Conto e registro interno coincidono") (controllo delle @Time(state.LastReconciledAt))</li>
}
</ul>
</section>
}
</div>
var shownPositions = v.Positions.Where(p => _filter is null || p.Broker == _filter).ToList();
<section class="panel" aria-labelledby="posizioni">
<div class="panel-head">
<h2 id="posizioni">Posizioni aperte</h2>
<div class="panel-tools">
<nav class="segmented" aria-label="Conto">
<a href="/conti" class="@(_filter is null ? "on" : null)" aria-current="@(_filter is null ? "true" : null)">Tutti i conti</a>
@foreach (var a in v.Accounts)
{
<a href="/conti?conto=@a.Broker" class="@(_filter == a.Broker ? "on" : null)" aria-current="@(_filter == a.Broker ? "true" : null)">@a.Name</a>
}
</nav>
<a class="btn" href="/api/conti/posizioni.csv@(_filter is null ? "" : "?conto=" + _filter)" download><Icon Name="download" Size="18" />Esporta CSV</a>
</div>
</div>
@if (shownPositions.Count == 0)
{
<p class="note">Nessuna posizione aperta@(_filter is null ? "" : " su questo conto").</p>
}
else
{
<div class="table-wrap">
<table class="table positions">
<thead>
<tr>
<th scope="col">Strumento</th>
<th scope="col" class="wide">Conto</th>
<th scope="col" class="wide">Strategia</th>
<th scope="col" class="num wide">Quantità</th>
<th scope="col" class="num wide">Prezzo medio</th>
<th scope="col" class="num wide">Prezzo ora</th>
<th scope="col" class="num">Valore</th>
<th scope="col" class="num">Risultato</th>
<th scope="col" class="num wide">Stop</th>
<th scope="col" class="num wide">Aperta da</th>
</tr>
</thead>
<tbody>
@foreach (var p in shownPositions)
{
var gain = p.ResultEur >= 0;
<tr>
<th scope="row"><strong>@p.Symbol</strong> <span class="muted">@p.Name</span></th>
<td class="wide">@(p.Broker == Venues.Alpaca ? "Alpaca" : "OKX")</td>
<td class="nowrap wide"><span class="swatch round" style="background: var(--s-@p.Strategy.Replace('_', '-'))"></span>@StrategyNames.Label(p.Strategy)</td>
<td class="num wide">@Format.Quantity(p.Quantity)</td>
<td class="num wide">@Format.Money(p.Average, p.Currency)</td>
<td class="num wide">@Format.Money(p.Last, p.Currency)</td>
<td class="num"><strong>@Shell.Money(p.ValueEur, c)</strong></td>
<td class="num nowrap @(gain ? "gain" : "loss")"><strong>@Shell.Money(p.ResultEur, c, withSign: true)<span class="cell-extra"> (@Format.Percent(p.Percent, 2, withSign: true))</span></strong></td>
<td class="num wide">@(p.Stop is { } stop ? Format.Money(stop, p.Currency, decimals: AccountsView.StopDecimals(stop)) : "—")</td>
<td class="num wide nowrap">@Age(p.OpenedAt)</td>
</tr>
}
</tbody>
<tfoot>
<tr>
<th scope="row">Totale</th>
<td class="wide"></td><td class="wide"></td><td class="wide"></td><td class="wide"></td><td class="wide"></td>
<td class="num"><strong>@Shell.Money(shownPositions.Sum(p => p.ValueEur), c)</strong></td>
<td class="num @(shownPositions.Sum(p => p.ResultEur) >= 0 ? "gain" : "loss")"><strong>@Shell.Money(shownPositions.Sum(p => p.ResultEur), c, withSign: true)</strong></td>
<td class="wide"></td><td class="wide"></td>
</tr>
</tfoot>
</table>
</div>
}
</section>
<div class="columns">
<section class="panel" aria-labelledby="ordini">
<div class="panel-head">
<h2 id="ordini">Ordini in attesa</h2>
<span class="note">@(v.PendingOthers == 0 ? (v.Pending.Count == 0 ? "Nessun ordine aperto" : "Solo stop di protezione: nessun acquisto in coda") : $"{v.PendingOthers} {(v.PendingOthers == 1 ? "ordine" : "ordini")} in corso oltre agli stop")</span>
</div>
@if (v.Pending.Count > 0)
{
<div class="table-wrap">
<table class="table pending">
<thead><tr><th scope="col">Ordine</th><th scope="col">Dove</th><th scope="col" class="num">Scatta a</th><th scope="col">Stato</th></tr></thead>
<tbody>
@foreach (var o in v.Pending)
{
<tr>
<th scope="row">@o.Action <strong>@o.Subject</strong></th>
<td>@o.Where</td>
<td class="num @(o.Level == "vedi tabella sopra" ? "muted" : null)">@o.Level</td>
<td><span class="order-state">@if (o.Waiting) {<Icon Name="clock" Size="16" />} else {<span class="dot"></span>}@o.Status</span></td>
</tr>
}
</tbody>
</table>
</div>
}
@if (v.AlpacaStops)
{
<p class="aside">Le azioni intere hanno uno stop permanente sul broker, che resta attivo anche a bot spento. Sulle frazioni il broker accetta solo ordini che valgono un giorno: quelli li rimetto a ogni apertura e, a mercato chiuso, li sorveglio io.</p>
}
</section>
<section class="panel" aria-labelledby="valute">
<h2 id="valute">In quale valuta sono i soldi</h2>
@{
var dollars = v.Accounts.Where(a => a.Currency == "USD").Sum(a => a.Eur(a.Equity));
var euros = v.TotalEur - dollars;
var parts = Format.Shares([dollars, euros]);
}
<div class="split-bar slim" role="img" aria-label="Dollari @Format.Percent(parts[0]), euro @Format.Percent(parts[1])">
@if (parts[0] > 0) {<span style="width: @Css(parts[0])%; background: var(--text-2)"></span>}
@if (parts[1] > 0) {<span style="width: @Css(parts[1])%; background: var(--cash)"></span>}
</div>
<dl class="currency-lines">
<dt><span class="swatch" style="background: var(--text-2)"></span>Dollari (conto Alpaca)</dt><dd><strong>@Shell.Money(dollars, c)</strong> <span class="muted">@Format.Percent(parts[0])</span></dd>
<dt><span class="swatch" style="background: var(--cash)"></span>Euro e crypto (conto OKX)</dt><dd><strong>@Shell.Money(euros, c)</strong> <span class="muted">@Format.Percent(parts[1])</span></dd>
</dl>
<p class="note">@RateText(v)@(v.FxEffect is { } fx && fx != 0 ? $" Effetto del cambio sul risultato in euro: {Format.Money(fx, "EUR", withSign: true)}." : "")</p>
@if (dollars > 0)
{
<p class="notice notice-attention fx-warning"><Icon Name="alert" Size="16" />Se il dollaro perde il 5% sull'euro, il totale scende di circa @Format.Money(Math.Round(dollars * 0.05m), "EUR", decimals: 0) anche a prezzi fermi.</p>
}
</section>
</div>
@if (v.Residues.Count > 0)
{
<section class="panel" aria-labelledby="residui">
<div class="panel-head">
<h2 id="residui">Residui sotto il minimo vendibile</h2>
<span class="note">Restano sul conto ma non sono più del bot: tolti dal registro al valore di mercato</span>
</div>
<div class="table-wrap">
<table class="table">
<thead><tr><th scope="col">Strumento</th><th scope="col">Conto</th><th scope="col" class="num">Quantità</th><th scope="col" class="num">Valore</th><th scope="col" class="num">Dal</th></tr></thead>
<tbody>
@foreach (var r in v.Residues)
{
<tr><th scope="row">@r.Symbol</th><td>@r.Broker</td><td class="num">@Format.Quantity(r.Quantity)</td><td class="num">@Format.Money(r.Value, r.Currency)</td><td class="num">@Format.ShortDate(r.At, Shell.Now, Shell.Zone, withTime: false)</td></tr>
}
</tbody>
</table>
</div>
</section>
}
}
@code {
private AccountsView _view = null!;
private string _currency = "EUR";
private string? _filter;
private string? _message;
private bool _ok;
private Dictionary<Guid, int>? _latency;
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
[SupplyParameterFromQuery(Name = "conto")]
public string? Conto { get; set; }
[SupplyParameterFromQuery(Name = "ok")]
public string? Ok { get; set; }
[SupplyParameterFromQuery(Name = "errore")]
public string? Errore { get; set; }
protected override async Task LoadAsync()
{
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
var services = Host.Services!;
_currency = Shell.Effective((await services.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value);
_view = await AccountsView.LoadAsync(services, Clock, Shell.Zone, ct);
_filter = Conto is Venues.Okx or Venues.Alpaca ? Conto : null;
(_message, _ok) = (Ok, Errore) switch
{
("allinea", _) => ("Fatto: il registro ha preso i numeri del conto e il conto è tornato normale.", true),
("escludi", _) => ("Fatto: la differenza resta fuori dal registro e il conto è tornato normale.", true),
(_, "motore") => ("Il motore di trading non è attivo: riprova tra poco.", false),
(_, "chiave") => ("Una chiave che permette i prelievi non si allinea: va sostituita in Impostazioni.", false),
(_, "presto") => ("La scelta si fa dopo 15 minuti di modalità prudente: prima la differenza può ancora spiegarsi da sola.", false),
(_, { }) => ("Non è stato possibile completare la scelta: riprova.", false),
_ => (null, false),
};
using var aggregates = Shell.Aggregates();
if (aggregates is not null)
{
var names = aggregates.RootElement.GetProperty("conti").EnumerateArray().Select(x => x.GetProperty("risposta_ms").GetInt32()).ToList();
_latency = _view.Accounts.Select((a, i) => (a.Id, i)).Where(x => x.i < names.Count).ToDictionary(x => x.Id, x => names[x.i]);
}
}
private string Connection(AccountCard a)
{
if (a.State.LastOutcome == ReconcileOutcomes.Unreachable)
{
return "Il broker non risponde";
}
if (_latency?.GetValueOrDefault(a.Id) is > 0 and var ms)
{
return $"Connesso, risposta in {ms} ms";
}
return a.Environment == TradingEnvironments.Simulation ? "Attivo, nel simulatore" : "Connesso";
}
private static string Holdings(AccountCard a) => (a.Broker, a.Holdings) switch
{
(_, 0) => "nulla",
(Venues.Alpaca, 1) => "1 azione",
(Venues.Alpaca, var n) => $"{n} azioni",
(_, 1) => "1 moneta",
(_, var n) => $"{n} monete",
};
private static string RateText(AccountsView v, bool withSource = true) => v.UsdRate is { } rate
? $"Cambio usato: 1 € = {Format.Quantity(rate)} $" + (withSource ? $" (BCE, {AccountsView.DayMonth(new DateTimeOffset(v.RateDay!.Value.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero))})." : ".")
: "Manca ancora il cambio euro/dollaro della BCE: i dollari restano nella loro valuta.";
private static decimal Part(decimal part, decimal total) => total == 0 ? 0 : part / total * 100m;
private static string Css(decimal percent) => percent.ToString("0.###", CultureInfo.InvariantCulture);
private string Time(DateTimeOffset? moment) => moment is { } m ? TimeZoneInfo.ConvertTime(m, Shell.Zone).ToString("HH:mm", CultureInfo.InvariantCulture) : "—";
private string Age(DateTimeOffset opened)
{
var days = (int)Math.Floor((Shell.Now - opened).TotalDays);
return days switch
{
< 1 => "oggi",
1 => "1 giorno",
_ => $"{days} giorni",
};
}
}