Fase 3 — Conti, ordini, contabilità #89
No files matched your search
@@ -19,7 +19,7 @@ Dalla radice del repository: `./tasks.ps1 <comando>` (Windows) o `sh ./tasks.sh
|
||||
- `ci`: come la CI. Esegue `check`, poi i test su PostgreSQL (avvia `docker compose up -d --wait postgres`, porta 55432) e infine l'immagine. Richiede Docker.
|
||||
- `hooks`: attiva `.githooks/pre-commit`, che esegue `check` prima di ogni commit. Si fa una volta per copia del repository.
|
||||
- `seed-demo`: la modalità dimostrativa con i dati dell'appendice F, in una cartella e un database a parte, solo dal computer stesso.
|
||||
- `screenshots`: fotografa Panoramica, Diario e Impostazioni a 1440 px (chiaro e scuro) e a 390 px in `artifacts/screenshots/`. Usa Edge o Chrome già installati.
|
||||
- `screenshots`: fotografa Panoramica, Conti, Diario e Impostazioni a 1440 px (chiaro e scuro) e a 390 px in `artifacts/screenshots/`. Usa Edge o Chrome già installati.
|
||||
- `desktop-win` (Fase 10): non ancora disponibile.
|
||||
- `docker compose up --build`: l'applicazione su http://localhost:8787 con PostgreSQL, `/health` risponde `ok`. Primo accesso con `ANUBIS_ADMIN_PASSWORD` del compose.
|
||||
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Anubis.Core;
|
||||
using Anubis.Data;
|
||||
using Anubis.Db;
|
||||
using Anubis.Trading;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
/// <summary>One account of the Conti screen, in its own currency and in euro.</summary>
|
||||
internal sealed record AccountCard(Guid Id, string Name, string Broker, string Environment, string Currency, decimal Cash, decimal Invested, decimal InvestedEur, int Holdings,
|
||||
decimal Realized, decimal Unrealized, decimal Fees, decimal Flows, AccountState State, decimal Rate)
|
||||
{
|
||||
/// <summary>Cash plus the positions, each valued to the cent as the table shows it, so the figures add up on screen.</summary>
|
||||
public decimal Equity => Cash + Invested;
|
||||
|
||||
public string Kind => Broker == Venues.Alpaca ? "Azioni USA" : "Crypto";
|
||||
|
||||
public string Short => Broker == Venues.Alpaca ? "Alpaca" : "OKX";
|
||||
|
||||
public decimal Result => Equity - Flows;
|
||||
|
||||
public decimal Percent => Flows > 0m ? Result / Flows * 100m : 0m;
|
||||
|
||||
/// <summary>An amount of this account in euro, at the latest rate.</summary>
|
||||
public decimal Eur(decimal amount) => Currency == "EUR" || Rate <= 0m ? amount : amount / Rate;
|
||||
}
|
||||
|
||||
internal sealed record PositionRow(Guid AccountId, string Broker, string Symbol, string Name, string Strategy, decimal Quantity, decimal Average, decimal Last, decimal? Stop,
|
||||
string Currency, DateTimeOffset OpenedAt, decimal ValueEur, decimal ResultEur)
|
||||
{
|
||||
public decimal Percent => Average == 0m ? 0m : (Last / Average - 1m) * 100m;
|
||||
}
|
||||
|
||||
/// <summary>A line of "Ordini in attesa": one order, or the stops of Alpaca grouped by validity.</summary>
|
||||
internal sealed record PendingRow(string Action, string Subject, string Where, string Level, string Status, bool Waiting);
|
||||
|
||||
internal sealed record ResidueRow(string Broker, string Symbol, decimal Quantity, decimal Value, string Currency, DateTimeOffset At);
|
||||
|
||||
internal sealed record StrategySlice(string Label, string Color, decimal Eur);
|
||||
|
||||
/// <summary>
|
||||
/// The Conti e posizioni screen (SPEC 13.6, mockup 02): totals, accounts with key and reconciliation, open positions,
|
||||
/// pending orders, residues and where the money is by currency. One world only: real accounts when there are any,
|
||||
/// otherwise the simulated ones, so finto and vero never add up (SPEC 7.1).
|
||||
/// </summary>
|
||||
internal sealed record AccountsView(
|
||||
IReadOnlyList<AccountCard> Accounts,
|
||||
IReadOnlyList<PositionRow> Positions,
|
||||
IReadOnlyList<PendingRow> Pending,
|
||||
int PendingOthers,
|
||||
bool AlpacaStops,
|
||||
IReadOnlyList<ResidueRow> Residues,
|
||||
IReadOnlyList<StrategySlice> Slices,
|
||||
decimal? UsdRate,
|
||||
DateOnly? RateDay,
|
||||
decimal? FxEffect,
|
||||
bool MarketOpen,
|
||||
DateTimeOffset MarketNext)
|
||||
{
|
||||
public bool HasAccounts => Accounts.Count > 0;
|
||||
|
||||
public decimal TotalEur => Accounts.Sum(a => a.Eur(a.Equity));
|
||||
|
||||
public decimal CashEur => Accounts.Sum(a => a.Eur(a.Cash));
|
||||
|
||||
public decimal InvestedEur => Accounts.Sum(a => a.InvestedEur);
|
||||
|
||||
public decimal ResultEur => Accounts.Sum(a => a.Eur(a.Result));
|
||||
|
||||
public decimal OpenResultEur => Positions.Sum(p => p.ResultEur);
|
||||
|
||||
public static async Task<AccountsView> LoadAsync(AppServices services, IClock clock, TimeZoneInfo zone, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(services);
|
||||
var ledger = services.Trading?.Ledger ?? new Ledger(services.Db, clock);
|
||||
var reconciler = services.Trading?.Reconciler ?? new Reconciler(services.Db, clock, ledger);
|
||||
var fx = await new FxStore(services.Db, clock).LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false);
|
||||
var rate = fx?.Rate ?? 0m;
|
||||
|
||||
var (accounts, instruments, trades, orders, residues) = await services.Db.ReadAsync(async s =>
|
||||
{
|
||||
var a = await s.QueryAsync("SELECT id, name, broker, environment, base_currency FROM accounts ORDER BY broker DESC, created_at",
|
||||
r => (Id: r.Id("id"), Name: r.Text("name"), Broker: r.Text("broker"), Environment: r.Text("environment"), Currency: r.Text("base_currency"))).ConfigureAwait(false);
|
||||
var i = await s.QueryAsync("SELECT id, symbol, name, quote_currency FROM instruments",
|
||||
r => (Id: r.Id("id"), Symbol: r.Text("symbol"), Name: r.TextOrNull("name"), Quote: r.TextOrNull("quote_currency"))).ConfigureAwait(false);
|
||||
var t = await s.QueryAsync("SELECT account_id, realized, fees FROM trades", r => (Account: r.Id("account_id"), Realized: r.Money("realized"), Fees: r.Money("fees")))
|
||||
.ConfigureAwait(false);
|
||||
var o = await s.QueryAsync(
|
||||
"SELECT account_id, instrument_id, side, order_type, purpose, quantity, filled_quantity, limit_price, stop_price, time_in_force, step, created_at, updated_at FROM orders " +
|
||||
"WHERE status IN ('created', 'submitted', 'partially_filled') ORDER BY created_at, id",
|
||||
r => new OpenOrder(r.Id("account_id"), r.Id("instrument_id"), r.Text("side"), r.Text("order_type"), r.TextOrNull("purpose") ?? "entry", r.Money("quantity"),
|
||||
r.MoneyOrNull("filled_quantity") ?? 0m, r.MoneyOrNull("limit_price"), r.MoneyOrNull("stop_price"), r.TextOrNull("time_in_force") ?? "day",
|
||||
r.IsNull("step") ? null : (int)r.Number("step"), r.Moment("created_at"), r.Moment("updated_at"))).ConfigureAwait(false);
|
||||
var res = await s.QueryAsync("SELECT account_id, instrument_id, quantity, value, currency, created_at FROM residues ORDER BY created_at DESC",
|
||||
r => (Account: r.Id("account_id"), Instrument: r.Id("instrument_id"), Quantity: r.Money("quantity"), Value: r.Money("value"), Currency: r.Text("currency"),
|
||||
At: r.Moment("created_at"))).ConfigureAwait(false);
|
||||
return (a, i.ToDictionary(x => x.Id), t, o, res);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var world = accounts.Any(a => TradingEnvironments.World(a.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated;
|
||||
accounts = accounts.Where(a => TradingEnvironments.World(a.Environment) == world).ToList();
|
||||
var shown = accounts.Select(a => a.Id).ToHashSet();
|
||||
var equities = (await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false)).Where(e => shown.Contains(e.AccountId)).ToList();
|
||||
var positions = (await ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false)).Where(p => shown.Contains(p.AccountId)).ToList();
|
||||
|
||||
var rates = accounts.ToDictionary(a => a.Id, a => a.Currency == "USD" ? rate : 1m);
|
||||
decimal Eur(Guid account, decimal amount) => rates[account] is var r && r > 0m && r != 1m ? amount / r : amount;
|
||||
var currencies = accounts.ToDictionary(a => a.Id, a => a.Currency);
|
||||
var rows = positions
|
||||
.Select(p =>
|
||||
{
|
||||
var instrument = instruments.GetValueOrDefault(p.InstrumentId);
|
||||
var value = Math.Round(p.Value, 2, MidpointRounding.AwayFromZero);
|
||||
return (Native: value, Row: new PositionRow(p.AccountId, accounts.First(a => a.Id == p.AccountId).Broker, instrument.Symbol ?? "?", instrument.Name ?? "", p.Strategy,
|
||||
p.Quantity, p.AveragePrice, p.LastPrice ?? p.AveragePrice, p.StopPrice, instrument.Quote ?? currencies[p.AccountId], p.OpenedAt,
|
||||
Math.Round(Eur(p.AccountId, value), 2, MidpointRounding.AwayFromZero), Math.Round(Eur(p.AccountId, p.Unrealized), 2, MidpointRounding.AwayFromZero)));
|
||||
})
|
||||
.OrderByDescending(r => r.Row.ValueEur)
|
||||
.ToList();
|
||||
|
||||
var cards = new List<AccountCard>();
|
||||
foreach (var a in accounts)
|
||||
{
|
||||
var mine = equities.Where(e => e.AccountId == a.Id).ToList();
|
||||
var held = positions.Where(p => p.AccountId == a.Id).ToList();
|
||||
var valued = rows.Where(r => r.Row.AccountId == a.Id).ToList();
|
||||
var state = await reconciler.StateAsync(a.Id, cancellationToken).ConfigureAwait(false);
|
||||
cards.Add(new AccountCard(a.Id, a.Name, a.Broker, a.Environment, a.Currency, mine.Sum(e => e.Cash), valued.Sum(r => r.Native), valued.Sum(r => r.Row.ValueEur),
|
||||
held.Select(p => p.InstrumentId).Distinct().Count(), trades.Where(t => t.Account == a.Id).Sum(t => t.Realized), held.Sum(p => p.Unrealized),
|
||||
trades.Where(t => t.Account == a.Id).Sum(t => t.Fees), mine.Sum(e => e.Flows), state, rates[a.Id]));
|
||||
}
|
||||
|
||||
var byId = cards.ToDictionary(c => c.Id);
|
||||
var market = MarketState(services.MarketData?.UsCalendar, clock.UtcNow);
|
||||
var (pending, others, alpacaStops) = PendingRows(orders.Where(o => shown.Contains(o.Account)).ToList(), byId, instruments.ToDictionary(i => i.Key, i => i.Value.Symbol),
|
||||
positions, market.Open, market.Next, clock.UtcNow, zone);
|
||||
|
||||
var slices = Strategies.Base.Select(b => new StrategySlice(Strategies.Label(b.Name, withMarket: true), "var(--s-" + b.Name.Replace('_', '-') + ")",
|
||||
rows.Where(r => r.Row.Strategy == b.Name).Sum(r => r.Row.ValueEur))).ToList();
|
||||
decimal? fxEffect = null;
|
||||
if (cards.Count > 0)
|
||||
{
|
||||
fxEffect = await services.Db.ReadAsync(s => s.FirstOrDefaultAsync(
|
||||
"SELECT fx_effect FROM equity_snapshots WHERE scope = 'total' AND world = @w ORDER BY taken_at DESC LIMIT 1", r => r.MoneyOrNull("fx_effect"), ("w", world)),
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var residueRows = residues.Where(r => shown.Contains(r.Account))
|
||||
.Select(r => new ResidueRow(byId[r.Account].Short, instruments.GetValueOrDefault(r.Instrument).Symbol ?? "?", r.Quantity, r.Value, r.Currency, r.At)).ToList();
|
||||
return new AccountsView(cards, rows.Select(r => r.Row).ToList(), pending, others, alpacaStops, residueRows, slices, fx?.Rate, fx?.Date, fxEffect, market.Open, market.Next);
|
||||
}
|
||||
|
||||
/// <summary>The positions as CSV for a spreadsheet: semicolons, dot decimals, one row per position.</summary>
|
||||
public string Csv(string? broker)
|
||||
{
|
||||
var text = new StringBuilder("strumento;nome;conto;strategia;quantita;prezzo_medio;prezzo_ora;valuta;valore_eur;risultato_eur;stop;aperta_il\n");
|
||||
foreach (var p in Positions.Where(p => broker is null || p.Broker == broker))
|
||||
{
|
||||
text.Append(string.Join(';', Clean(p.Symbol), Clean(p.Name), p.Broker, p.Strategy, Number(p.Quantity), Number(p.Average), Number(p.Last), p.Currency,
|
||||
Number(Math.Round(p.ValueEur, 2)), Number(Math.Round(p.ResultEur, 2)), p.Stop is { } stop ? Number(stop) : "",
|
||||
p.OpenedAt.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture))).Append('\n');
|
||||
}
|
||||
|
||||
return text.ToString();
|
||||
|
||||
static string Number(decimal value) => value.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
static string Clean(string value) => value.Replace(';', ',').Replace('\n', ' ');
|
||||
}
|
||||
|
||||
private sealed record OpenOrder(Guid Account, Guid Instrument, string Side, string Kind, string Purpose, decimal Quantity, decimal Filled, decimal? Limit, decimal? Stop,
|
||||
string Tif, int? Step, DateTimeOffset CreatedAt, DateTimeOffset UpdatedAt);
|
||||
|
||||
private static (List<PendingRow> Rows, int Others, bool AlpacaStops) PendingRows(List<OpenOrder> orders, Dictionary<Guid, AccountCard> accounts, Dictionary<Guid, string> symbols,
|
||||
IReadOnlyList<LedgerPosition> positions, bool marketOpen, DateTimeOffset marketNext, DateTimeOffset now, TimeZoneInfo zone)
|
||||
{
|
||||
var rows = new List<PendingRow>();
|
||||
var others = 0;
|
||||
foreach (var o in orders.Where(o => o.Purpose != "stop"))
|
||||
{
|
||||
others++;
|
||||
var account = accounts[o.Account];
|
||||
var verb = o.Side == "buy" ? "Compra" : "Vendi";
|
||||
var level = o.Limit is { } limit ? Format.Money(limit, account.Currency) : "a mercato";
|
||||
var status = o.Step is { } step && o.Kind == "limit" ? $"Passo {Math.Min(step + 1, 4)} di 4, dalle {Local(o.CreatedAt, zone)}" : "In corso dalle " + Local(o.CreatedAt, zone);
|
||||
rows.Add(new PendingRow($"{verb} {Format.Quantity(o.Quantity - o.Filled)}", symbols.GetValueOrDefault(o.Instrument) ?? "?", account.Short, level, status, false));
|
||||
}
|
||||
|
||||
var stops = orders.Where(o => o.Purpose == "stop").ToList();
|
||||
foreach (var o in stops.Where(o => accounts[o.Account].Broker != Venues.Alpaca).OrderByDescending(o => (o.Quantity - o.Filled) * (o.Stop ?? 0m)))
|
||||
{
|
||||
var account = accounts[o.Account];
|
||||
var local = TimeZoneInfo.ConvertTime(o.UpdatedAt, zone);
|
||||
var status = local.Date == TimeZoneInfo.ConvertTime(now, zone).Date && o.UpdatedAt > o.CreatedAt
|
||||
? "Attivo, aggiornato oggi alle " + local.ToString("HH:mm", CultureInfo.InvariantCulture)
|
||||
: "Attivo dal " + DayMonth(TimeZoneInfo.ConvertTime(o.CreatedAt, zone));
|
||||
rows.Add(new PendingRow("Vendi " + Format.Quantity(o.Quantity - o.Filled), symbols.GetValueOrDefault(o.Instrument) ?? "?", account.Short,
|
||||
o.Stop is { } stop ? Format.Money(stop, account.Currency, decimals: StopDecimals(stop)) : "", status, false));
|
||||
}
|
||||
|
||||
var alpaca = stops.Where(o => accounts[o.Account].Broker == Venues.Alpaca).ToList();
|
||||
var alpacaHeld = positions.Where(p => accounts.TryGetValue(p.AccountId, out var a) && a.Broker == Venues.Alpaca && p.StopPrice is not null).ToList();
|
||||
var gtc = alpaca.Count(o => o.Tif == "gtc");
|
||||
var fractions = alpacaHeld.Count(p => p.Quantity != decimal.Truncate(p.Quantity));
|
||||
if (gtc > 0)
|
||||
{
|
||||
rows.Add(new PendingRow(gtc == 1 ? "1 stop permanente" : $"{gtc} stop permanenti", "sulle azioni intere", "Alpaca", "vedi tabella sopra", gtc == 1 ? "Attivo" : "Attivi", false));
|
||||
}
|
||||
|
||||
if (fractions > 0)
|
||||
{
|
||||
var opens = Local(marketNext, zone);
|
||||
rows.Add(new PendingRow(fractions == 1 ? "1 stop giornaliero" : $"{fractions} stop giornalieri", "sulle frazioni di azione", "Alpaca", "vedi tabella sopra",
|
||||
marketOpen ? "Attivi fino alla chiusura delle " + opens : "In coda per l'apertura delle " + opens, !marketOpen));
|
||||
}
|
||||
|
||||
return (rows, others, gtc > 0 || fractions > 0);
|
||||
}
|
||||
|
||||
/// <summary>Whether the US market is open now, and its next close (open) or next open (closed).</summary>
|
||||
public static (bool Open, DateTimeOffset Next) MarketState(IMarketCalendar? calendar, DateTimeOffset now)
|
||||
{
|
||||
var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(now, Zones.NewYork).DateTime);
|
||||
foreach (var useCalendar in new[] { true, false })
|
||||
{
|
||||
for (var d = -1; d <= 8; d++)
|
||||
{
|
||||
var day = today.AddDays(d);
|
||||
var session = useCalendar ? calendar?.SessionOn(day) : Regular(day);
|
||||
if (session is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (now >= session.OpenUtc && now < session.CloseUtc)
|
||||
{
|
||||
return (true, session.CloseUtc);
|
||||
}
|
||||
|
||||
if (session.OpenUtc > now)
|
||||
{
|
||||
return (false, session.OpenUtc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (false, now);
|
||||
}
|
||||
|
||||
/// <summary>A regular session, 9:30 to 16:00 in New York on weekdays: used only when the broker's calendar is not there yet.</summary>
|
||||
private static MarketSession? Regular(DateOnly day)
|
||||
{
|
||||
if (day.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
DateTimeOffset At(int hour, int minute)
|
||||
{
|
||||
var local = day.ToDateTime(new TimeOnly(hour, minute));
|
||||
return new DateTimeOffset(local, Zones.NewYork.GetUtcOffset(local)).ToUniversalTime();
|
||||
}
|
||||
|
||||
return new MarketSession(day, At(9, 30), At(16, 0));
|
||||
}
|
||||
|
||||
private static string Local(DateTimeOffset moment, TimeZoneInfo zone) => TimeZoneInfo.ConvertTime(moment, zone).ToString("HH:mm", CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>Stops of a thousand or more without cents when they are round (66.180 €), the others with cents (166,00 $).</summary>
|
||||
public static int StopDecimals(decimal stop) => stop >= 1000m && stop == decimal.Truncate(stop) ? 0 : 2;
|
||||
|
||||
public static string DayMonth(DateTimeOffset local)
|
||||
{
|
||||
var text = Format.LongDate(DateOnly.FromDateTime(local.DateTime));
|
||||
return text[..text.LastIndexOf(' ')];
|
||||
}
|
||||
}
|
||||
@@ -387,6 +387,15 @@ internal sealed partial class AnubisHost(
|
||||
Wake();
|
||||
}
|
||||
|
||||
/// <summary>Stops and rebuilds the services, so that new broker keys take effect: a few seconds of "avvio".</summary>
|
||||
internal async Task RestartServicesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
using (await ExclusiveAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
await ResetAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Market data needs the network: off in demo mode (SPEC 13.7), when <c>ANUBIS_MARKET_DATA</c> is <c>off</c>, and
|
||||
/// in tests unless they bring their own fake network.
|
||||
|
||||
@@ -325,6 +325,67 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
|
||||
.chart-table summary { color: var(--link); cursor: pointer; }
|
||||
.chart-table .table-wrap { max-height: 280px; overflow: auto; margin-top: 8px; }
|
||||
|
||||
/* ---- Conti e posizioni ---- */
|
||||
.muted { color: var(--text-3); font-weight: 400; }
|
||||
.attention { color: var(--attention); }
|
||||
.panel-head { display: flex; align-items: center; justify-content: space-between; gap: 12px 16px; flex-wrap: wrap; margin-bottom: 12px; }
|
||||
.panel-head h2 { margin: 0; }
|
||||
.panel-tools { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
|
||||
.totals { padding: 24px 28px; }
|
||||
.totals-cells { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; }
|
||||
.total-value { font-size: 30px; line-height: 36px; font-weight: 650; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; }
|
||||
.cell-note { color: var(--text-3); font-size: 13px; }
|
||||
.split-bar { display: flex; gap: 3px; height: 12px; margin-top: 24px; }
|
||||
.split-bar span { border-radius: 3px; min-width: 3px; }
|
||||
.split-bar.slim { height: 12px; margin: 16px 0 12px; }
|
||||
.split-legend { list-style: none; display: flex; flex-wrap: wrap; gap: 6px 28px; margin: 12px 0 0; padding: 0; color: var(--text-2); font-size: 13.5px; }
|
||||
.split-legend li { display: inline-flex; align-items: center; gap: 8px; }
|
||||
.split-legend strong { color: var(--text); font-weight: 600; }
|
||||
.swatch { display: inline-block; width: 11px; height: 11px; border-radius: 2px; flex: none; margin-right: 8px; vertical-align: -1px; }
|
||||
.swatch.round { width: 8px; height: 8px; border-radius: 50%; }
|
||||
.split-legend .swatch { margin-right: 0; }
|
||||
.account-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(380px, 1fr)); gap: 20px; }
|
||||
.account { display: flex; flex-direction: column; padding: 22px 26px; }
|
||||
.account-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
|
||||
.account-head h2 { display: flex; align-items: center; gap: 10px; }
|
||||
.tag { padding: 2px 8px; border-radius: 6px; background: var(--surface-2); color: var(--text-2); font-size: 13px; font-weight: 500; line-height: 20px; }
|
||||
.link-state { display: inline-flex; align-items: center; gap: 8px; color: var(--text-2); font-size: 13.5px; }
|
||||
.link-state.down .dot { background: var(--loss); }
|
||||
.account-value { display: flex; align-items: baseline; gap: 14px; flex-wrap: wrap; margin: 14px 0 12px; }
|
||||
.account-equity { font-size: 32px; line-height: 40px; font-weight: 650; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; }
|
||||
.account-native, .native { color: var(--text-3); font-size: 13.5px; font-weight: 400; }
|
||||
.native { margin-left: 0.35em; }
|
||||
.account-lines { display: grid; grid-template-columns: minmax(0, 1fr) auto; margin: 0; font-variant-numeric: tabular-nums; }
|
||||
.account-lines dt, .account-lines dd { padding: 9px 0; border-top: 1px solid var(--rule-inner); margin: 0; }
|
||||
.account-lines dt { color: var(--text-2); }
|
||||
.account-lines dd { text-align: right; }
|
||||
.account-lines strong { font-weight: 600; }
|
||||
.account-facts { list-style: none; margin: 16px 0 0; padding: 12px 16px; border-radius: 10px; background: var(--surface-2); display: flex; flex-direction: column; gap: 6px; font-size: 13.5px; color: var(--text-2); }
|
||||
.account-facts li { display: flex; align-items: flex-start; gap: 10px; }
|
||||
.account-facts .icon { margin-top: 2px; color: var(--text-3); }
|
||||
.account-facts .loss .icon, .account-facts .attention .icon { color: inherit; }
|
||||
.prudent { margin-top: 16px; }
|
||||
.prudent > div { display: flex; flex-direction: column; gap: 8px; }
|
||||
.differences { margin: 0; padding-left: 18px; }
|
||||
.choices { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
.choices form { margin: 0; }
|
||||
.positions th[scope="row"] { font-weight: 400; text-align: left; white-space: nowrap; }
|
||||
.positions th[scope="row"] strong { font-weight: 650; }
|
||||
.table tbody tr:last-child td, .table tbody tr:last-child th { border-bottom: 0; }
|
||||
.table tfoot th, .table tfoot td { padding: 12px 12px 4px 0; border-top: 2px solid var(--text); text-align: left; }
|
||||
.table tfoot .num { text-align: right; }
|
||||
.table th[scope="row"] { padding: 10px 12px 10px 0; border-bottom: 1px solid var(--rule-inner); vertical-align: top; }
|
||||
.pending th[scope="row"], .positions th[scope="row"] { color: var(--text); }
|
||||
.pending th[scope="row"] { font-weight: 400; text-align: left; }
|
||||
.pending th[scope="row"] strong { font-weight: 650; }
|
||||
.order-state { display: inline-flex; align-items: center; gap: 8px; }
|
||||
.order-state .icon { color: var(--text-3); }
|
||||
.aside { margin-top: 16px; padding: 12px 16px; border-radius: 10px; background: var(--surface-2); color: var(--text-2); font-size: 13.5px; }
|
||||
.currency-lines { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 6px 16px; margin: 0 0 12px; font-variant-numeric: tabular-nums; }
|
||||
.currency-lines dt { display: flex; align-items: center; color: var(--text-2); }
|
||||
.currency-lines dd { margin: 0; text-align: right; }
|
||||
.fx-warning { margin-top: 16px; }
|
||||
|
||||
/* ---- Service pages ---- */
|
||||
.service { min-height: 100vh; display: flex; justify-content: center; padding: 48px 16px; }
|
||||
.service-box { width: 100%; max-width: 720px; display: flex; flex-direction: column; gap: 16px; }
|
||||
@@ -362,6 +423,16 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
|
||||
.statement { font-size: 18px; line-height: 26px; margin-top: 12px; }
|
||||
.columns { grid-template-columns: 1fr; }
|
||||
.row { grid-template-columns: 1fr; }
|
||||
.totals { padding: 18px; }
|
||||
.totals-cells { grid-template-columns: 1fr 1fr; gap: 14px; }
|
||||
.total-value { font-size: 22px; line-height: 28px; }
|
||||
.split-legend { gap: 6px 16px; }
|
||||
.account-grid { grid-template-columns: 1fr; gap: 14px; }
|
||||
.account { padding: 18px; }
|
||||
.account-equity { font-size: 28px; line-height: 34px; }
|
||||
.positions .wide { display: none; }
|
||||
.account-value .cell-change { display: inline-flex; flex-basis: 100%; }
|
||||
.panel-tools { width: 100%; justify-content: space-between; }
|
||||
.facts { grid-template-columns: 1fr; gap: 2px; }
|
||||
.facts dd { margin-bottom: 8px; }
|
||||
.bottombar {
|
||||
|
||||
@@ -35,6 +35,9 @@
|
||||
case "dots":
|
||||
<circle cx="5.5" cy="12" r="1" /><circle cx="12" cy="12" r="1" /><circle cx="18.5" cy="12" r="1" />
|
||||
break;
|
||||
case "download":
|
||||
<path d="M12 4v11M7 10.5l5 5 5-5M5 19.5h14" />
|
||||
break;
|
||||
case "collapse":
|
||||
<path d="m11 17-5-5 5-5M18 17l-5-5 5-5" />
|
||||
break;
|
||||
|
||||
@@ -1,5 +1,413 @@
|
||||
@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>
|
||||
|
||||
<Pending Title="Nessun conto collegato.">Conti, posizioni e ordini arrivano con la contabilità: lì aggiungerai le chiavi dei conti di prova e vedrai patrimonio, liquidità e commissioni di ciascuno.</Pending>
|
||||
@{
|
||||
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>@Strategies.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),
|
||||
(_, { }) => ("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",
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,12 @@
|
||||
@inject ShellData Shell
|
||||
@inject SecondFactorDrafts Drafts
|
||||
@inject Anubis.Core.IClock Clock
|
||||
@using Anubis.Data
|
||||
@using Anubis.Trading
|
||||
|
||||
<PageTitle>Impostazioni · Anubis</PageTitle>
|
||||
|
||||
@* First part of SPEC 13.5: appearance, security, system. The other sections arrive with their phases. *@
|
||||
@* SPEC 13.5: appearance, accounts and keys, data, security, system. The other sections arrive with their phases. *@
|
||||
@if (Ok is { } ok)
|
||||
{
|
||||
<p class="notice notice-gain" role="status"><Icon Name="check" Size="16" />@(ok switch
|
||||
@@ -16,6 +18,9 @@
|
||||
"due-fattori" => "Secondo fattore attivato.",
|
||||
"due-fattori-tolti" => "Secondo fattore disattivato.",
|
||||
"salvataggio" => "Salvataggio fatto.",
|
||||
"chiavi" => "Chiavi verificate e salvate: possono fare ordini e non possono prelevare. Il motore è ripartito e le usa.",
|
||||
"chiavi-tolte" => "Chiavi tolte: quel conto torna al simulatore interno per le strategie che non hanno ancora storia sul conto di prova.",
|
||||
"capitale" => "Capitale affidato aggiornato e diviso tra le strategie.",
|
||||
_ => "Fatto.",
|
||||
})</p>
|
||||
}
|
||||
@@ -25,7 +30,7 @@
|
||||
}
|
||||
|
||||
<nav class="tabs" aria-label="Sezioni delle impostazioni">
|
||||
<a href="#aspetto">Aspetto</a><a href="#dati">Dati</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
|
||||
<a href="#aspetto">Aspetto</a><a href="#conti">Conti</a><a href="#dati">Dati</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
|
||||
</nav>
|
||||
|
||||
<section class="panel" id="aspetto">
|
||||
@@ -56,6 +61,80 @@
|
||||
<p class="hint">Gli importi in dollari usano il cambio del giorno, che arriva con i dati di mercato. Fino ad allora restano in euro.</p>
|
||||
</section>
|
||||
|
||||
<section class="panel" id="conti">
|
||||
<h2>Conti e chiavi</h2>
|
||||
<p class="hint">In questa fase uso solo denaro finto: il simulatore interno è sempre acceso e, con le chiavi dei conti di prova, le strategie passano ai conti di prova dei broker. Le chiavi di conti veri non servono e non vanno inserite.</p>
|
||||
@foreach (var b in _brokers)
|
||||
{
|
||||
<h3>@b.Title</h3>
|
||||
<dl class="facts">
|
||||
@foreach (var k in b.Keys)
|
||||
{
|
||||
<dt>@k.Label</dt><dd>@KeyState(k.Status)</dd>
|
||||
}
|
||||
@if (b.State is { KeyCheckedAt: { } checkedAt } state)
|
||||
{
|
||||
<dt>Permessi</dt>
|
||||
<dd class="@(state.KeyCanWithdraw == true ? "loss" : null)">@(state.KeyCanWithdraw == true ? "Permette i prelievi: va sostituita, intanto niente nuovi acquisti" : state.KeyCanTrade == true ? "Legge e fa ordini, nessun prelievo" : "Solo lettura") (verificati @Inline(Format.ShortDate(checkedAt, Shell.Now, Shell.Zone)))</dd>
|
||||
}
|
||||
</dl>
|
||||
@if (Shell.IsDemo)
|
||||
{
|
||||
<p class="hint">Nella modalità dimostrativa chiavi e capitale non si cambiano.</p>
|
||||
}
|
||||
else if (b.Keys.Any(k => k.Status.FromEnvironment))
|
||||
{
|
||||
<p class="hint">Le chiavi arrivano dalle variabili d'ambiente e valgono più di quelle salvate qui: si cambiano nella configurazione del container.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<form method="post" action="/azioni/chiavi/@b.Broker" class="form" autocomplete="off">
|
||||
<AntiforgeryToken />
|
||||
@foreach (var k in b.Keys)
|
||||
{
|
||||
<label for="k-@k.Name">@k.Label</label>
|
||||
<input id="k-@k.Name" name="@k.Name" type="password" autocomplete="off" spellcheck="false" maxlength="512" required />
|
||||
}
|
||||
<button class="btn" type="submit">Verifica e salva</button>
|
||||
</form>
|
||||
<p class="hint">Non le rimostro mai. Prima di salvarle chiedo al broker cosa possono fare: una chiave che permette i prelievi la rifiuto. Dopo il salvataggio il motore riparte da solo, in pochi secondi.</p>
|
||||
@if (b.Keys.Any(k => k.Status.IsSet))
|
||||
{
|
||||
<form method="post" action="/azioni/chiavi/@b.Broker/togli" class="form-inline"><AntiforgeryToken /><button class="btn btn-small" type="submit" data-confirm="Tolgo le chiavi di @b.Short? Le posizioni sul conto di prova restano lì, ma il bot non le segue più finché non le rimetti.">Togli le chiavi</button></form>
|
||||
}
|
||||
}
|
||||
|
||||
<h4>Capitale affidato a @b.Short</h4>
|
||||
@if (b.Entrusted is { } e)
|
||||
{
|
||||
<p>@Format.Money(e.AmountEur, "EUR")@(e.Currency == "EUR" ? "" : $", cioè {Format.Money(e.Amount, e.Currency)} al cambio di {Format.Quantity(e.FxRate)}"), deciso @Inline(Format.ShortDate(e.At, Shell.Now, Shell.Zone)) da @e.ChangedBy.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p>Nessun capitale affidato: le strategie di @b.Short osservano soltanto.</p>
|
||||
}
|
||||
@if (b.Strategies.Count > 0)
|
||||
{
|
||||
<ul class="plain">
|
||||
@foreach (var s in b.Strategies)
|
||||
{
|
||||
<li>@Strategies.Label(s.Strategy, withMarket: true): quota @Format.Percent(s.Share * 100m, 0), capitale @Format.Money(s.Capital, s.Currency), liquidità @Format.Money(s.Cash, s.Currency)</li>
|
||||
}
|
||||
</ul>
|
||||
}
|
||||
@if (!Shell.IsDemo)
|
||||
{
|
||||
<form method="post" action="/azioni/capitale/@b.Broker" class="form-inline">
|
||||
<AntiforgeryToken />
|
||||
<label for="euro-@b.Broker">Nuovo importo in euro</label>
|
||||
<input id="euro-@b.Broker" name="euro" inputmode="decimal" autocomplete="off" value="@(b.Entrusted is { } cur ? Format.Quantity(cur.AmountEur) : "")" required />
|
||||
<button class="btn btn-small" type="submit">Salva</button>
|
||||
</form>
|
||||
<p class="hint">Si divide tra le strategie del conto secondo le quote@(b.Broker == Venues.Alpaca ? ", in dollari al cambio BCE del giorno" : ""). Ridurlo non vende nulla: se una strategia ha investito più di quanto le resterebbe, aspetto che venda.</p>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
|
||||
<section class="panel" id="dati">
|
||||
<h2>Dati</h2>
|
||||
@if (Host.Services!.MarketData is not { } market)
|
||||
@@ -217,6 +296,12 @@
|
||||
|
||||
@code {
|
||||
private readonly List<SettingValue> _appearance = [];
|
||||
private readonly List<BrokerSetup> _brokers = [];
|
||||
|
||||
private sealed record BrokerKey(string Name, string Label, SecretStatus Status);
|
||||
|
||||
private sealed record BrokerSetup(string Broker, string Title, string Short, IReadOnlyList<BrokerKey> Keys, AccountState? State, EntrustedCapital? Entrusted,
|
||||
IReadOnlyList<StrategyCapital> Strategies);
|
||||
private IReadOnlyList<Anubis.Data.SourceState> _sources = [];
|
||||
private SettingValue _meetings = new(SettingsStore.CentralBankMeetings.Key, "", false, null);
|
||||
private List<SettingChange> _history = [];
|
||||
@@ -244,6 +329,21 @@
|
||||
_meetings = await services.Settings.GetAsync(SettingsStore.CentralBankMeetings.Key, ct);
|
||||
_sources = await new Anubis.Data.SourceStateStore(services.Db, Clock).ListAsync(ct);
|
||||
_backups = services.Backups.List();
|
||||
var ledger = new Ledger(services.Db, Clock);
|
||||
var capital = new Capital(services.Db, Clock, ledger, new FxStore(services.Db, Clock));
|
||||
var reconciler = new Reconciler(services.Db, Clock, ledger);
|
||||
foreach (var (broker, title, name) in new[] { (Venues.Okx, "OKX Europe · conto demo", "OKX"), (Venues.Alpaca, "Alpaca · conto di prova (paper)", "Alpaca") })
|
||||
{
|
||||
var keys = new List<BrokerKey>();
|
||||
foreach (var (secret, label) in TradingService.KeyFields(broker))
|
||||
{
|
||||
keys.Add(new BrokerKey(secret, label, await services.Secrets.StatusAsync(secret, ct)));
|
||||
}
|
||||
|
||||
var demoAccount = await services.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT id FROM accounts WHERE broker = @b AND environment = 'demo'", r => (Guid?)r.Id("id"), ("b", broker)), ct);
|
||||
var state = demoAccount is { } id ? await reconciler.StateAsync(id, ct) : null;
|
||||
_brokers.Add(new BrokerSetup(broker, title, name, keys, state, await capital.EntrustedAsync(broker, ct), await capital.StrategiesAsync(broker, ct)));
|
||||
}
|
||||
var user = HttpContext!.User;
|
||||
_hasSecondFactor = CurrentUser.HasSecondFactor(user);
|
||||
if (!_hasSecondFactor && !Shell.IsDemo)
|
||||
@@ -262,9 +362,30 @@
|
||||
"impostazione" => "Questa impostazione non si può cambiare così.",
|
||||
"riunioni" => "L'elenco delle riunioni non è valido: una riga per riunione, con FED o BCE e la data, per esempio «FED 2027-01-27».",
|
||||
"bot" => "Comando non ammesso nello stato attuale del bot.",
|
||||
"motore" => "Il motore di trading non è attivo (modalità dimostrativa o ANUBIS_TRADING spento): qui non si cambia nulla.",
|
||||
"conto" => "Conto sconosciuto.",
|
||||
"ambiente" => "Le chiavi di questo conto arrivano dalle variabili d'ambiente: si cambiano nella configurazione del container.",
|
||||
"chiavi-vuote" => "Servono tutti i campi della chiave.",
|
||||
"chiavi-rifiutate" => "Il broker non ha accettato la chiave, o non ha risposto. Controlla di aver copiato la chiave del conto di prova e riprova. Non ho salvato nulla.",
|
||||
"prelievo" => "Questa chiave permette i prelievi: non la salvo. Creane una senza il permesso di prelievo.",
|
||||
"sola-lettura" => "Questa chiave può solo leggere: per lavorare sul conto di prova serve anche il permesso di fare ordini. Non l'ho salvata.",
|
||||
"importo" => "Scrivi un importo in euro, per esempio 4000 o 1.500,50.",
|
||||
"cambio" => "Manca ancora il cambio euro/dollaro della BCE: lo scarico ogni giorno, riprova più tardi.",
|
||||
"capitale" => "Una strategia ha investito più di quanto le resterebbe: potrò ridurre il capitale quando avrà venduto.",
|
||||
_ => PasswordMessages.For(Errore),
|
||||
};
|
||||
|
||||
private string KeyState(SecretStatus status) => status switch
|
||||
{
|
||||
{ FromEnvironment: true } => "Dalle variabili d'ambiente",
|
||||
{ IsSet: true, UpdatedAt: { } at } => "Impostata " + Inline(Format.ShortDate(at, Shell.Now, Shell.Zone)),
|
||||
{ IsSet: true } => "Impostata",
|
||||
_ => "Non impostata",
|
||||
};
|
||||
|
||||
// "Oggi 08:20" inside a sentence reads "oggi 08:20".
|
||||
private static string Inline(string text) => text.Length == 0 ? text : char.ToLowerInvariant(text[0]) + text[1..];
|
||||
|
||||
private static string SourceName(string source) => source switch
|
||||
{
|
||||
"okx" => "OKX Europe (crypto)",
|
||||
|
||||
@@ -9,6 +9,10 @@
|
||||
var o = _overview;
|
||||
var c = _currency;
|
||||
}
|
||||
@if (!o.CapitalSet && !Shell.IsDemo)
|
||||
{
|
||||
<p class="notice notice-attention" role="status"><Icon Name="alert" Size="16" /><span>Primo passo: decidi quanto capitale affidare al bot in <a href="/impostazioni#conti">Impostazioni, Conti e chiavi</a>. Lì puoi anche inserire le chiavi dei conti di prova. Finché non c'è capitale, le strategie osservano soltanto.</span></p>
|
||||
}
|
||||
<section class="panel head-block" aria-label="Il punto della situazione">
|
||||
<div class="half half-past">
|
||||
<div class="half-head">
|
||||
|
||||
@@ -146,6 +146,16 @@ internal static partial class Endpoints
|
||||
return format == "md" ? Results.Text(report.ToMarkdown(), "text/markdown; charset=utf-8") : Results.Json(report, _json);
|
||||
});
|
||||
|
||||
// The open positions of the Conti screen as CSV (SPEC 13.6), all accounts or one broker's.
|
||||
api.MapGet("/conti/posizioni.csv", async (AnubisHost host, ShellData shell, IClock clock, string? conto, CancellationToken ct) =>
|
||||
{
|
||||
var view = await AccountsView.LoadAsync(host.Services!, clock, shell.Zone, ct).ConfigureAwait(false);
|
||||
var broker = conto is Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca ? conto : null;
|
||||
var day = TimeZoneInfo.ConvertTime(clock.UtcNow, shell.Zone).ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
|
||||
return Results.File(System.Text.Encoding.UTF8.GetPreamble().Concat(System.Text.Encoding.UTF8.GetBytes(view.Csv(broker))).ToArray(),
|
||||
"text/csv; charset=utf-8", $"anubis-posizioni-{day}.csv");
|
||||
});
|
||||
|
||||
// The external sources and the live feed: what is on, what is off and why (SPEC 4.4).
|
||||
api.MapGet("/data/sources", async (AnubisHost host, IClock clock, CancellationToken ct) =>
|
||||
{
|
||||
|
||||
@@ -30,6 +30,10 @@ internal static partial class Forms
|
||||
signed.MapPost("/impostazioni/{key}", SetSettingAsync);
|
||||
signed.MapPost("/bot/{command}", BotAsync);
|
||||
signed.MapPost("/salvataggio", BackupAsync);
|
||||
signed.MapPost("/conti/{id:guid}/{choice}", ResolveAccountAsync);
|
||||
signed.MapPost("/chiavi/{broker}", SaveKeysAsync);
|
||||
signed.MapPost("/chiavi/{broker}/togli", RemoveKeysAsync);
|
||||
signed.MapPost("/capitale/{broker}", SetCapitalAsync);
|
||||
}
|
||||
|
||||
private static string Back(IFormCollection form, string fallback)
|
||||
@@ -172,6 +176,165 @@ internal static partial class Forms
|
||||
return Results.Redirect(ok ? back : With(back, "errore", "bot"));
|
||||
}
|
||||
|
||||
/// <summary>The user's choice for an account in prudent mode after the 15 minutes (SPEC 7.4): align or leave out.</summary>
|
||||
private static async Task<IResult> ResolveAccountAsync(Guid id, string choice, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
if (choice is not ("allinea" or "escludi"))
|
||||
{
|
||||
return Results.Redirect("/conti?errore=scelta");
|
||||
}
|
||||
|
||||
if (host.IsDemo || host.Services?.Trading is not { } trading || trading.ManagerOf(id) is not { } manager)
|
||||
{
|
||||
return Results.Redirect("/conti?errore=motore");
|
||||
}
|
||||
|
||||
var state = await trading.Reconciler.StateAsync(id, ct).ConfigureAwait(false);
|
||||
if (state.ModeReason == Anubis.Trading.Reconciler.KeyReason)
|
||||
{
|
||||
return Results.Redirect("/conti?errore=chiave");
|
||||
}
|
||||
|
||||
await trading.Reconciler.ResolveAsync(manager, choice == "allinea" ? Anubis.Trading.ReconcileChoice.Align : Anubis.Trading.ReconcileChoice.Exclude,
|
||||
context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
||||
return Results.Redirect("/conti?ok=" + choice);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// New practice keys for a broker (SPEC 13.5): asked to the broker first, kept only if they may trade and may not
|
||||
/// withdraw (SPEC 2.2), saved encrypted, never shown again. The engine then restarts to use them.
|
||||
/// </summary>
|
||||
private static async Task<IResult> SaveKeysAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
const string back = "/impostazioni";
|
||||
if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca))
|
||||
{
|
||||
return Results.Redirect(back + "?errore=conto#conti");
|
||||
}
|
||||
|
||||
if (host.IsDemo || host.Services is not { Trading: { } trading } services)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=motore#conti");
|
||||
}
|
||||
|
||||
var fields = Anubis.Trading.TradingService.KeyFields(broker);
|
||||
foreach (var (name, _) in fields)
|
||||
{
|
||||
if ((await services.Secrets.StatusAsync(name, ct).ConfigureAwait(false)).FromEnvironment)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=ambiente#conti");
|
||||
}
|
||||
}
|
||||
|
||||
var values = fields.Select(f => form[f.Name].ToString().Trim()).ToList();
|
||||
if (values.Any(v => v.Length == 0 || v.Length > 512))
|
||||
{
|
||||
return Results.Redirect(back + "?errore=chiavi-vuote#conti");
|
||||
}
|
||||
|
||||
Anubis.Trading.KeyPermissions permissions;
|
||||
try
|
||||
{
|
||||
permissions = await trading.TestKeysAsync(broker, values, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Anubis.Trading.BrokerException)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=chiavi-rifiutate#conti");
|
||||
}
|
||||
|
||||
if (permissions.CanWithdraw)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=prelievo#conti");
|
||||
}
|
||||
|
||||
if (!permissions.CanTrade)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=sola-lettura#conti");
|
||||
}
|
||||
|
||||
var who = context.User.Identity?.Name ?? "utente";
|
||||
for (var i = 0; i < fields.Count; i++)
|
||||
{
|
||||
await services.Secrets.SetAsync(fields[i].Name, values[i], who, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await host.RestartServicesAsync(ct).ConfigureAwait(false);
|
||||
await WaitBrieflyAsync(host).ConfigureAwait(false);
|
||||
return Results.Redirect(back + "?ok=chiavi#conti");
|
||||
}
|
||||
|
||||
private static async Task<IResult> RemoveKeysAsync(string broker, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
const string back = "/impostazioni";
|
||||
if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca) || host.IsDemo || host.Services is not { } services)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=conto#conti");
|
||||
}
|
||||
|
||||
var who = context.User.Identity?.Name ?? "utente";
|
||||
foreach (var (name, _) in Anubis.Trading.TradingService.KeyFields(broker))
|
||||
{
|
||||
await services.Secrets.RemoveAsync(name, who, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await host.RestartServicesAsync(ct).ConfigureAwait(false);
|
||||
await WaitBrieflyAsync(host).ConfigureAwait(false);
|
||||
return Results.Redirect(back + "?ok=chiavi-tolte#conti");
|
||||
}
|
||||
|
||||
/// <summary>The capital entrusted to a broker, in euro (SPEC 7.1, 8.6): only the user sets it.</summary>
|
||||
private static async Task<IResult> SetCapitalAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||
{
|
||||
const string back = "/impostazioni";
|
||||
if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca))
|
||||
{
|
||||
return Results.Redirect(back + "?errore=conto#conti");
|
||||
}
|
||||
|
||||
if (host.IsDemo || host.Services?.Trading is not { } trading)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=motore#conti");
|
||||
}
|
||||
|
||||
if (ParseEuro(form["euro"].ToString()) is not { } amount || amount < 0m || amount > 100_000_000m)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=importo#conti");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await trading.SetCapitalAsync(broker, amount, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Anubis.Trading.CapitalException ex) when (ex.Message.StartsWith("Manca il cambio", StringComparison.Ordinal))
|
||||
{
|
||||
return Results.Redirect(back + "?errore=cambio#conti");
|
||||
}
|
||||
catch (Anubis.Trading.CapitalException)
|
||||
{
|
||||
return Results.Redirect(back + "?errore=capitale#conti");
|
||||
}
|
||||
|
||||
return Results.Redirect(back + "?ok=capitale#conti");
|
||||
}
|
||||
|
||||
/// <summary>An amount as people type it: "1500", "1.500", "1500,50", "1.500,50", "1500.50".</summary>
|
||||
internal static decimal? ParseEuro(string text)
|
||||
{
|
||||
var clean = (text ?? "").Replace(" ", "", StringComparison.Ordinal).Replace("€", "", StringComparison.Ordinal);
|
||||
if (clean.Contains(',', StringComparison.Ordinal))
|
||||
{
|
||||
clean = clean.Replace(".", "", StringComparison.Ordinal).Replace(',', '.');
|
||||
}
|
||||
else if (clean.LastIndexOf('.') is var dot and >= 0 && clean.Length - dot - 1 == 3)
|
||||
{
|
||||
clean = clean.Replace(".", "", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
return decimal.TryParse(clean, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out var value)
|
||||
? Math.Round(value, 2, MidpointRounding.ToZero)
|
||||
: null;
|
||||
}
|
||||
|
||||
private static async Task<IResult> BackupAsync(IFormCollection form, AnubisHost host, ILogger<AnubisHost> logger, CancellationToken ct)
|
||||
{
|
||||
var services = host.Services!;
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
using Anubis.Core;
|
||||
using Anubis.Db;
|
||||
using Anubis.Trading;
|
||||
|
||||
namespace Anubis.Server;
|
||||
|
||||
public sealed record EquityPoint(DateTimeOffset At, DateOnly Day, decimal Equity, decimal? Benchmark);
|
||||
/// <summary>A point of the total: equity, the capital put in or taken out so far (cumulative) and the time-weighted index.</summary>
|
||||
public sealed record EquityPoint(DateTimeOffset At, DateOnly Day, decimal Equity, decimal? Benchmark, decimal Flows = 0m, decimal? Twr = null);
|
||||
|
||||
internal sealed record PeriodResult(string Label, decimal Amount, decimal Percent);
|
||||
|
||||
@@ -11,7 +13,11 @@ internal sealed record NextMove(string Time, string Text);
|
||||
|
||||
internal sealed record LastAction(string When, string Text);
|
||||
|
||||
/// <summary>The "Finora" and "Adesso e dopo" halves of the Panoramica (SPEC 13.2, 13.6), read from the database.</summary>
|
||||
/// <summary>
|
||||
/// The "Finora" and "Adesso e dopo" halves of the Panoramica (SPEC 13.2, 13.6), read from the database. One world
|
||||
/// only, as on the Conti screen: real money when there is a real account, otherwise the simulated one. Results leave
|
||||
/// out the capital put in or taken out (SPEC 7.5): the amount is net of flows, the percentage is time-weighted.
|
||||
/// </summary>
|
||||
internal sealed record Overview(
|
||||
IReadOnlyList<EquityPoint> Points,
|
||||
IReadOnlyList<EquityPoint> Series,
|
||||
@@ -23,7 +29,8 @@ internal sealed record Overview(
|
||||
int PositionsWithoutStop,
|
||||
int OpenOrders,
|
||||
IReadOnlyList<NextMove> Next,
|
||||
IReadOnlyList<LastAction> Last)
|
||||
IReadOnlyList<LastAction> Last,
|
||||
bool CapitalSet = true)
|
||||
{
|
||||
public static readonly IReadOnlyList<(string Key, string Label)> Periods = [("avvio", "Dall'avvio"), ("30", "30 giorni"), ("7", "7 giorni"), ("oggi", "Oggi")];
|
||||
|
||||
@@ -31,22 +38,29 @@ internal sealed record Overview(
|
||||
|
||||
public static async Task<Overview> LoadAsync(AppServices services, string period, DateTimeOffset now, TimeZoneInfo zone, CancellationToken cancellationToken)
|
||||
{
|
||||
var (points, positions, withoutStop, orders, journal) = await services.Db.ReadAsync(async s =>
|
||||
var (points, positions, withoutStop, orders, journal, capitalSet) = await services.Db.ReadAsync(async s =>
|
||||
{
|
||||
var environments = await s.QueryAsync("SELECT environment FROM accounts", r => r.Text("environment")).ConfigureAwait(false);
|
||||
var world = environments.Any(e => TradingEnvironments.World(e) == Worlds.Real) ? Worlds.Real : Worlds.Simulated;
|
||||
var mine = string.Join(", ", new[] { TradingEnvironments.Simulation, TradingEnvironments.Demo, TradingEnvironments.Live }.Where(e => TradingEnvironments.World(e) == world).Select(e => "'" + e + "'"));
|
||||
var p = await s.QueryAsync(
|
||||
"SELECT taken_at, equity, benchmark FROM equity_snapshots WHERE scope = 'total' ORDER BY taken_at",
|
||||
r => (At: r.Moment("taken_at"), Equity: r.Money("equity"), Benchmark: r.MoneyOrNull("benchmark"))).ConfigureAwait(false);
|
||||
var count = await s.CountAsync("SELECT COUNT(*) FROM positions").ConfigureAwait(false);
|
||||
var noStop = await s.CountAsync("SELECT COUNT(*) FROM positions WHERE stop_price IS NULL").ConfigureAwait(false);
|
||||
var open = await s.CountAsync("SELECT COUNT(*) FROM orders WHERE status IN ('new', 'submitted', 'accepted', 'partially_filled')").ConfigureAwait(false);
|
||||
"SELECT taken_at, equity, benchmark, flows, twr_index FROM equity_snapshots WHERE scope = 'total' AND world = @w ORDER BY taken_at",
|
||||
r => (At: r.Moment("taken_at"), Equity: r.Money("equity"), Benchmark: r.MoneyOrNull("benchmark"), Flows: r.MoneyOrNull("flows") ?? 0m, Twr: r.MoneyOrNull("twr_index")),
|
||||
("w", world)).ConfigureAwait(false);
|
||||
var held = (await s.QueryAsync($"SELECT p.quantity, p.stop_price FROM positions p JOIN accounts a ON a.id = p.account_id WHERE a.environment IN ({mine})",
|
||||
r => (Quantity: r.Money("quantity"), Stop: r.MoneyOrNull("stop_price"))).ConfigureAwait(false)).Where(x => x.Quantity > 0m).ToList();
|
||||
var open = await s.CountAsync(
|
||||
$"SELECT COUNT(*) FROM orders o JOIN accounts a ON a.id = o.account_id WHERE a.environment IN ({mine}) " +
|
||||
"AND o.status IN ('created', 'submitted', 'partially_filled') AND (o.purpose IS NULL OR o.purpose <> 'stop')").ConfigureAwait(false);
|
||||
var j = await s.QueryAsync("SELECT occurred_at, message FROM journal ORDER BY occurred_at DESC LIMIT 4",
|
||||
r => (At: r.Moment("occurred_at"), Text: r.Text("message"))).ConfigureAwait(false);
|
||||
return (p, count, noStop, open, j);
|
||||
var capital = await s.CountAsync("SELECT COUNT(*) FROM capital_changes").ConfigureAwait(false);
|
||||
return (p, held.Count, held.Count(x => x.Stop is null), open, j, capital > 0);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// One point per day: the last snapshot of each local day.
|
||||
var daily = points
|
||||
.Select(p => new EquityPoint(p.At, DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(p.At, zone).DateTime), p.Equity, p.Benchmark))
|
||||
.Select(p => new EquityPoint(p.At, DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(p.At, zone).DateTime), p.Equity, p.Benchmark, p.Flows, p.Twr))
|
||||
.GroupBy(p => p.Day)
|
||||
.Select(g => g.Last())
|
||||
.ToList();
|
||||
@@ -58,13 +72,19 @@ internal sealed record Overview(
|
||||
|
||||
if (daily.Count == 0)
|
||||
{
|
||||
return new Overview([], [], new PeriodResult("", 0, 0), default, 0, [], (int)positions, (int)withoutStop, (int)orders, next, last);
|
||||
return new Overview([], [], new PeriodResult("", 0, 0), default, 0, [], (int)positions, (int)withoutStop, (int)orders, next, last, capitalSet);
|
||||
}
|
||||
|
||||
var latest = daily[^1];
|
||||
EquityPoint Since(int days) => daily.LastOrDefault(p => p.Day <= latest.Day.AddDays(-days)) ?? daily[0];
|
||||
PeriodResult Between(string label, EquityPoint start) =>
|
||||
new(label, latest.Equity - start.Equity, start.Equity == 0 ? 0 : (latest.Equity - start.Equity) / start.Equity * 100m);
|
||||
PeriodResult Between(string label, EquityPoint start)
|
||||
{
|
||||
var amount = latest.Equity - start.Equity - (latest.Flows - start.Flows);
|
||||
var basis = start.Equity + (latest.Flows - start.Flows);
|
||||
var percent = start.Twr is > 0m && latest.Twr is { } twr ? (twr / start.Twr.Value - 1m) * 100m
|
||||
: basis == 0 ? 0 : amount / basis * 100m;
|
||||
return new PeriodResult(label, amount, percent);
|
||||
}
|
||||
|
||||
var start = period switch
|
||||
{
|
||||
@@ -80,6 +100,6 @@ internal sealed record Overview(
|
||||
cells.Add(new PeriodResult("Senza bot", lastBenchmark - firstBenchmark, (lastBenchmark - firstBenchmark) / firstBenchmark * 100m));
|
||||
}
|
||||
|
||||
return new Overview(daily, series, Between("", start), start.Day, start.Equity, cells, (int)positions, (int)withoutStop, (int)orders, next, last);
|
||||
return new Overview(daily, series, Between("", start), start.Day, start.Equity, cells, (int)positions, (int)withoutStop, (int)orders, next, last, capitalSet);
|
||||
}
|
||||
}
|
||||
+155
-12
@@ -12,12 +12,15 @@ namespace Anubis.Demo;
|
||||
/// Demo mode (SPEC 13.1, appendix F): a separate SQLite database in a new temporary folder, never the configured
|
||||
/// one (trap 27), filled with the rows of appendix F; the clock frozen at Friday 9 October 2026, 08:21 Italian
|
||||
/// time; no broker. Values that appendix F gives only as totals go to an aggregates file that only this mode reads.
|
||||
/// Rows of tables that later phases create (closed trades, news, models) are loaded by those phases.
|
||||
/// Rows of tables that later phases create (news, models) are loaded by those phases.
|
||||
/// </summary>
|
||||
public static class DemoMode
|
||||
{
|
||||
public const string AggregatesFile = "demo-aggregates.json";
|
||||
|
||||
/// <summary>The ECB rate of the demo's morning (F.2): one euro, 1,1601 dollars.</summary>
|
||||
public const decimal UsdRate = 1.1601m;
|
||||
|
||||
/// <summary>"Adesso" in the demo: Friday 9 October 2026, 08:21 in Rome.</summary>
|
||||
public static readonly DateTimeOffset Now = new(2026, 10, 9, 8, 21, 0, TimeSpan.FromHours(2));
|
||||
|
||||
@@ -109,34 +112,64 @@ public static class DemoMode
|
||||
await s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, 'OKX Europe', 'okx', 'simulation', 'EUR', @t), (@id2, 'Alpaca', 'alpaca', 'demo', 'USD', @t)",
|
||||
cancellationToken, ("id", okx), ("id2", alpaca), ("t", now)).ConfigureAwait(false);
|
||||
|
||||
var strategies = new Dictionary<string, (string Name, Guid Account, decimal Capital)>
|
||||
// F.2, F.3: capital in each account's currency, euro on OKX and dollars on Alpaca at the day's rate.
|
||||
var strategies = new Dictionary<string, (string Name, Guid Account, decimal Capital, decimal Cash, decimal Share)>
|
||||
{
|
||||
["Trend crypto"] = ("crypto_trend", okx, 4000m),
|
||||
["Momentum"] = ("equity_momentum", alpaca, 4500m),
|
||||
["Mean reversion"] = ("equity_meanrev", alpaca, 1500m),
|
||||
["Trend crypto"] = ("crypto_trend", okx, 4000m, 1905.10m, 1m),
|
||||
["Momentum"] = ("equity_momentum", alpaca, 5220.44m, 893.50m, 0.75m),
|
||||
["Mean reversion"] = ("equity_meanrev", alpaca, 1740.15m, 1236.71m, 0.25m),
|
||||
};
|
||||
foreach (var (name, account, capital) in strategies.Values)
|
||||
var currencyOf = new Dictionary<Guid, string> { [okx] = "EUR", [alpaca] = "USD" };
|
||||
foreach (var (name, account, capital, _, share) in strategies.Values)
|
||||
{
|
||||
await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at) VALUES (@id, @n, @a, 'simulation', @c, @st, @t, @t)",
|
||||
cancellationToken, ("id", ids.Next()), ("n", name), ("a", account), ("c", capital), ("st", new DbJson("{\"day\":58,\"of\":60}")), ("t", now)).ConfigureAwait(false);
|
||||
await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, share, state, created_at, updated_at) VALUES (@id, @n, @a, 'simulation', @c, @sh, @st, @t, @t)",
|
||||
cancellationToken, ("id", ids.Next()), ("n", name), ("a", account), ("c", capital), ("sh", share), ("st", new DbJson("{\"day\":58,\"of\":60}")), ("t", now))
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var started = now.AddDays(-60);
|
||||
await s.ExecuteAsync("INSERT INTO fx_rates (id, base, quote, rate_date, rate, source, created_at) VALUES (@id, 'EUR', 'USD', @d, @r, 'ecb', @t)",
|
||||
cancellationToken, ("id", ids.Next()), ("d", DateOnly.FromDateTime(Now.DateTime).ToString("yyyy-MM-dd", _it)), ("r", UsdRate), ("t", now.AddMinutes(-21)))
|
||||
.ConfigureAwait(false);
|
||||
foreach (var (broker, eur, currency, rate, amount) in new[] { ("okx", 4000m, "EUR", 1m, 4000m), ("alpaca", 6000m, "USD", UsdRate, 6960.59m) })
|
||||
{
|
||||
await s.ExecuteAsync("INSERT INTO capital_changes (id, broker, amount_eur, currency, fx_rate, amount, changed_by, created_at) VALUES (@id, @b, @e, @c, @r, @a, 'demo', @t)",
|
||||
cancellationToken, ("id", ids.Next()), ("b", broker), ("e", eur), ("c", currency), ("r", rate), ("a", amount), ("t", started)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// F.4: the ten open positions.
|
||||
var held = new List<(string Symbol, Guid Instrument, Guid Account, string Strategy, decimal Quantity, decimal Average, decimal Stop, DateTimeOffset Opened)>();
|
||||
foreach (var row in Csv("positions.csv").Skip(1))
|
||||
{
|
||||
var symbol = row[0];
|
||||
var crypto = symbol.Contains('/', StringComparison.Ordinal);
|
||||
var instrument = ids.Next();
|
||||
var (strategy, account, _) = strategies[row[3]];
|
||||
var (strategy, account, _, _, _) = strategies[row[3]];
|
||||
var opened = now.AddDays(-int.Parse(row[11], _it));
|
||||
await s.ExecuteAsync("INSERT INTO instruments (id, venue, symbol, name, asset_class, quote_currency, created_at) VALUES (@id, @v, @s, @n, @c, @q, @t)",
|
||||
cancellationToken, ("id", instrument), ("v", crypto ? "okx" : "alpaca"), ("s", symbol), ("n", row[1]), ("c", crypto ? "crypto" : "equity"),
|
||||
("q", crypto ? "EUR" : "USD"), ("t", now)).ConfigureAwait(false);
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO positions (id, account_id, instrument_id, strategy, quantity, average_price, last_price, stop_price, opened_at, created_at, updated_at) VALUES (@id, @a, @i, @s, @q, @p, @l, @st, @o, @t, @t)",
|
||||
cancellationToken, ("id", ids.Next()), ("a", account), ("i", instrument), ("s", strategy), ("q", Number(row[4])), ("p", Number(row[5])), ("l", Number(row[6])),
|
||||
("st", Number(row[10])), ("o", now.AddDays(-int.Parse(row[11], _it))), ("t", now)).ConfigureAwait(false);
|
||||
("st", Number(row[10])), ("o", opened), ("t", now)).ConfigureAwait(false);
|
||||
held.Add((symbol, instrument, account, strategy, Number(row[4]), Number(row[5]), Number(row[10]), opened));
|
||||
}
|
||||
|
||||
// Each strategy's cash: the capital given at the start, less what its positions and past trades took.
|
||||
foreach (var (name, account, capital, cash, _) in strategies.Values)
|
||||
{
|
||||
foreach (var (kind, amount, note) in new[] { ("capital", capital, "Capitale affidato"), ("buy", cash - capital, "Saldo di acquisti, vendite e commissioni") })
|
||||
{
|
||||
await s.ExecuteAsync("INSERT INTO cash_ledger (id, account_id, strategy, currency, amount, kind, note, occurred_at, created_at) VALUES (@id, @a, @s, @c, @m, @k, @n, @at, @t)",
|
||||
cancellationToken, ("id", ids.Next()), ("a", account), ("s", name), ("c", currencyOf[account]), ("m", amount), ("k", kind), ("n", note),
|
||||
("at", kind == "capital" ? started : now), ("t", now)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
await SeedTradesAsync(s, ids, strategies.Values.ToDictionary(v => v.Name, v => v.Account), currencyOf, held, now, cancellationToken).ConfigureAwait(false);
|
||||
await SeedStopsAndChecksAsync(s, ids, alpaca, held, rome, now, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
// F.6: the daily series of the total; accounts and strategies are generated to end on their F.2 and F.3 results.
|
||||
var daily = Csv("daily.csv").Skip(1).Select(r => (Day: DateOnly.ParseExact(r[0], "yyyy-MM-dd", _it), Equity: Number(r[1]), Benchmark: Number(r[2]), Drawdown: Number(r[3]))).ToList();
|
||||
var total = daily[^1].Equity - 10000m;
|
||||
@@ -151,12 +184,12 @@ public static class DemoMode
|
||||
foreach (var (day, equity, benchmark, drawdown) in daily)
|
||||
{
|
||||
var at = day == DateOnly.FromDateTime(Now.DateTime) ? now : new DateTimeOffset(day.ToDateTime(new TimeOnly(22, 0)), rome.GetUtcOffset(day.ToDateTime(new TimeOnly(22, 0))));
|
||||
await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, equity, benchmark, drawdown_pct, created_at) VALUES (@id, @at, 'total', @e, @b, @d, @t)",
|
||||
await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, world, currency, equity, benchmark, drawdown_pct, created_at) VALUES (@id, @at, 'total', 'simulated', 'EUR', @e, @b, @d, @t)",
|
||||
cancellationToken, ("id", ids.Next()), ("at", at), ("e", equity), ("b", benchmark), ("d", drawdown), ("t", now)).ConfigureAwait(false);
|
||||
foreach (var (scope, account, strategy, start, result) in series)
|
||||
{
|
||||
var value = Math.Round(start + (equity - 10000m) * result / total, 2, MidpointRounding.AwayFromZero);
|
||||
await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, account_id, strategy, equity, created_at) VALUES (@id, @at, @sc, @a, @st, @e, @t)",
|
||||
await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, world, currency, account_id, strategy, equity, created_at) VALUES (@id, @at, @sc, 'simulated', 'EUR', @a, @st, @e, @t)",
|
||||
cancellationToken, ("id", ids.Next()), ("at", at), ("sc", scope), ("a", account), ("st", strategy), ("e", value), ("t", now)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -176,6 +209,116 @@ public static class DemoMode
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// F.5: the 41 closed trades. Their net results add up to the "guadagni già incassati" of F.2; the commissions of
|
||||
// each account go on its first trade. Trades without a symbol in the appendix take one of the strategy's.
|
||||
private static async Task SeedTradesAsync(DbSession s, IdSource ids, Dictionary<string, Guid> accountOf, Dictionary<Guid, string> currencyOf,
|
||||
List<(string Symbol, Guid Instrument, Guid Account, string Strategy, decimal Quantity, decimal Average, decimal Stop, DateTimeOffset Opened)> held,
|
||||
DateTimeOffset now, CancellationToken cancellationToken)
|
||||
{
|
||||
var prices = held.ToDictionary(h => h.Symbol, h => h.Average);
|
||||
var names = new Dictionary<string, string>();
|
||||
foreach (var (symbol, name, price) in new[]
|
||||
{
|
||||
("TSLA", "Tesla", 250m), ("PG", "Procter & Gamble", 160m), ("LINK/EUR", "Chainlink", 15m), ("V", "Visa", 290m), ("ADA/EUR", "Cardano", 0.6m),
|
||||
("AMD", "AMD", 160m), ("UNH", "UnitedHealth", 520m), ("KO", "Coca-Cola", 68m), ("MSFT", "Microsoft", 420m),
|
||||
})
|
||||
{
|
||||
prices[symbol] = price;
|
||||
names[symbol] = name;
|
||||
}
|
||||
|
||||
var instruments = held.ToDictionary(h => h.Symbol, h => h.Instrument);
|
||||
var fallback = new Dictionary<string, string[]>
|
||||
{
|
||||
["crypto_trend"] = ["BTC/EUR", "ETH/EUR", "SOL/EUR"],
|
||||
["equity_momentum"] = ["AVGO", "NVDA", "LLY", "JPM", "XOM", "COST"],
|
||||
["equity_meanrev"] = ["AAPL", "PG", "V", "KO", "MSFT"],
|
||||
};
|
||||
var fees = new Dictionary<Guid, decimal> { [accountOf["crypto_trend"]] = 14.49m, [accountOf["equity_momentum"]] = Math.Round(0.33m * UsdRate, 2) };
|
||||
var rows = Csv("trades.csv").Skip(1).ToList();
|
||||
|
||||
// In dollars each trade is rounded to the cent; the last one of the account takes the rounding, so the total
|
||||
// converts back to the euro of F.2 exactly.
|
||||
var left = rows.GroupBy(r => accountOf[r[1]]).ToDictionary(g => g.Key, g => (Count: g.Count(), Total: Math.Round(g.Sum(r => Number(r[2])) * (currencyOf[g.Key] == "EUR" ? 1m : UsdRate), 2,
|
||||
MidpointRounding.AwayFromZero)));
|
||||
for (var i = 0; i < rows.Count; i++)
|
||||
{
|
||||
var (strategy, eur) = (rows[i][1], Number(rows[i][2]));
|
||||
var symbol = rows[i].Length > 3 && rows[i][3].Length > 0 ? rows[i][3] : fallback[strategy][i % fallback[strategy].Length];
|
||||
var account = accountOf[strategy];
|
||||
if (!instruments.TryGetValue(symbol, out var instrument))
|
||||
{
|
||||
var crypto = symbol.Contains('/', StringComparison.Ordinal);
|
||||
instrument = ids.Next();
|
||||
instruments[symbol] = instrument;
|
||||
await s.ExecuteAsync("INSERT INTO instruments (id, venue, symbol, name, asset_class, quote_currency, created_at) VALUES (@id, @v, @s, @n, @c, @q, @t)",
|
||||
cancellationToken, ("id", instrument), ("v", crypto ? "okx" : "alpaca"), ("s", symbol), ("n", names[symbol]), ("c", crypto ? "crypto" : "equity"), ("q", crypto ? "EUR" : "USD"), ("t", now))
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var currency = currencyOf[account];
|
||||
var (count, total) = left[account];
|
||||
var realized = count == 1 ? total : currency == "EUR" ? eur : Math.Round(eur * UsdRate, 2, MidpointRounding.AwayFromZero);
|
||||
left[account] = (count - 1, total - realized);
|
||||
var fee = fees.Remove(account, out var first) ? first : 0m;
|
||||
var bought = 600m;
|
||||
var quantity = Math.Round(bought / prices[symbol], 6);
|
||||
var closed = now.AddDays(-(rows.Count - i)).AddHours(-3);
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO trades (id, account_id, instrument_id, strategy, status, opened_at, closed_at, bought_quantity, bought_value, sold_quantity, sold_value, fees, realized, exit_reason, created_at, updated_at) " +
|
||||
"VALUES (@id, @a, @i, @s, 'closed', @o, @c, @q, @b, @q, @sv, @f, @r, @e, @t, @t)",
|
||||
cancellationToken, ("id", ids.Next()), ("a", account), ("i", instrument), ("s", strategy), ("o", closed.AddDays(-5)), ("c", closed), ("q", quantity), ("b", bought),
|
||||
("sv", bought + realized + fee), ("f", fee), ("r", realized), ("e", realized >= 0m ? "signal" : "stop"), ("t", now)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
// F.7: the protective stops. On OKX one stop for each coin; on Alpaca a permanent stop on the whole shares, while
|
||||
// the day stops on the fractions wait for the opening (the market is closed at 08:21). Both accounts were checked
|
||||
// at 08:20 and agree with the ledger; the keys may trade but not withdraw.
|
||||
private static async Task SeedStopsAndChecksAsync(DbSession s, IdSource ids, Guid alpaca,
|
||||
List<(string Symbol, Guid Instrument, Guid Account, string Strategy, decimal Quantity, decimal Average, decimal Stop, DateTimeOffset Opened)> held,
|
||||
TimeZoneInfo rome, DateTimeOffset now, CancellationToken cancellationToken)
|
||||
{
|
||||
DateTimeOffset Local(int daysAgo, int hour, int minute)
|
||||
{
|
||||
var local = DateOnly.FromDateTime(Now.DateTime).AddDays(-daysAgo).ToDateTime(new TimeOnly(hour, minute));
|
||||
return new DateTimeOffset(local, rome.GetUtcOffset(local)).ToUniversalTime();
|
||||
}
|
||||
|
||||
var okxSince = new Dictionary<string, (DateTimeOffset Created, DateTimeOffset Updated)>
|
||||
{
|
||||
["BTC/EUR"] = (Local(4, 2, 6), Local(0, 2, 6)),
|
||||
["ETH/EUR"] = (Local(2, 9, 14), Local(2, 9, 14)),
|
||||
["SOL/EUR"] = (Local(6, 11, 40), Local(6, 11, 40)),
|
||||
};
|
||||
var n = 0;
|
||||
foreach (var h in held)
|
||||
{
|
||||
var whole = decimal.Truncate(h.Quantity);
|
||||
var onAlpaca = h.Account == alpaca;
|
||||
if (onAlpaca && whole == 0m)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var (created, updated) = onAlpaca ? (h.Opened, h.Opened) : okxSince[h.Symbol];
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO orders (id, account_id, instrument_id, strategy, client_order_id, broker_order_id, side, order_type, quantity, stop_price, status, purpose, time_in_force, " +
|
||||
"filled_quantity, submitted_at, created_at, updated_at) VALUES (@id, @a, @i, @s, @c, @b, 'sell', 'stop', @q, @st, 'submitted', 'stop', 'gtc', 0, @cr, @cr, @up)",
|
||||
cancellationToken, ("id", ids.Next()), ("a", h.Account), ("i", h.Instrument), ("s", h.Strategy), ("c", $"ANU-DEMO-STOP-{++n:00}"), ("b", $"demo-{n:00}"),
|
||||
("q", onAlpaca ? whole : h.Quantity), ("st", h.Stop), ("cr", created), ("up", updated)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var checkedAt = Local(0, 8, 20);
|
||||
foreach (var account in held.Select(h => h.Account).Distinct())
|
||||
{
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO account_status (id, account_id, mode, last_reconciled_at, last_outcome, key_can_trade, key_can_withdraw, key_checked_at, created_at, updated_at) " +
|
||||
"VALUES (@id, @a, 'normal', @at, 'clean', @yes, @no, @at, @t, @t)",
|
||||
cancellationToken, ("id", ids.Next()), ("a", account), ("at", checkedAt), ("yes", true), ("no", false), ("t", now)).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads the aggregates file of a demo folder.</summary>
|
||||
public static JsonDocument? ReadAggregates(DataDirectory data)
|
||||
{
|
||||
|
||||
@@ -21,6 +21,15 @@ public static class Strategies
|
||||
public static string BrokerOf(string strategy) =>
|
||||
Base.FirstOrDefault(b => b.Name == strategy).Broker ?? throw new ArgumentException($"Unknown strategy '{strategy}'.", nameof(strategy));
|
||||
|
||||
/// <summary>The name the user reads (appendix F): short in tables, with the market in legends.</summary>
|
||||
public static string Label(string strategy, bool withMarket = false) => strategy switch
|
||||
{
|
||||
CryptoTrend => "Trend crypto",
|
||||
EquityMomentum => withMarket ? "Momentum azioni" : "Momentum",
|
||||
EquityMeanrev => withMarket ? "Mean reversion azioni" : "Mean reversion",
|
||||
_ => strategy,
|
||||
};
|
||||
|
||||
/// <summary>The currency a broker's ledger is kept in: euro on OKX Europe, dollars on Alpaca (SPEC 7.1).</summary>
|
||||
public static string CurrencyOf(string broker) => broker == Venues.Alpaca ? "USD" : "EUR";
|
||||
|
||||
|
||||
@@ -450,6 +450,37 @@ public sealed partial class TradingService : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The secrets of a broker's practice keys, in the order the settings form asks for them.</summary>
|
||||
public static IReadOnlyList<(string Name, string Label)> KeyFields(string broker) => broker == Venues.Alpaca
|
||||
? [("ALPACA_API_KEY_DEMO", "Chiave (API key ID)"), ("ALPACA_API_SECRET_DEMO", "Segreto (secret key)")]
|
||||
: [("OKX_API_KEY_DEMO", "Chiave (API key)"), ("OKX_API_SECRET_DEMO", "Segreto (secret key)"), ("OKX_API_PASSPHRASE_DEMO", "Passphrase")];
|
||||
|
||||
/// <summary>
|
||||
/// Asks the broker what new practice keys may do, before they are saved: a key that may withdraw is never kept
|
||||
/// (SPEC 2.2). Throws <see cref="BrokerException"/> when the broker refuses the key or does not answer.
|
||||
/// </summary>
|
||||
public async Task<KeyPermissions> TestKeysAsync(string broker, IReadOnlyList<string> values, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(values);
|
||||
foreach (var value in values)
|
||||
{
|
||||
Redactor.Register(value);
|
||||
}
|
||||
|
||||
IBrokerAccount account = broker == Venues.Alpaca
|
||||
? new AlpacaTrading(_http, _clock, new AlpacaCredentials(values[0], values[1]), new AlpacaTradingOptions { Environment = TradingEnvironments.Demo }, _consent, _sockets)
|
||||
: new OkxTrading(_http, _clock, new OkxCredentials(values[0], values[1], values[2]),
|
||||
new OkxTradingOptions { Environment = TradingEnvironments.Demo, QuoteCurrency = "EUR" }, _consent, _sockets);
|
||||
try
|
||||
{
|
||||
return await account.GetKeyPermissionsAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
(account as IDisposable)?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private IBrokerAccount? Build(AccountContext account, AlpacaCredentials? alpaca, OkxCredentials? okx)
|
||||
{
|
||||
switch (account.Environment)
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
using System.Net;
|
||||
using Anubis.Db;
|
||||
using Anubis.Server;
|
||||
|
||||
namespace Anubis.Tests;
|
||||
|
||||
/// <summary>The Conti e posizioni screen and the accounts part of Impostazioni (issue #32).</summary>
|
||||
[TestClass]
|
||||
public sealed class AccountsScreenTests
|
||||
{
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task TheDemoShowsTheFiguresOfTheMockup()
|
||||
{
|
||||
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
|
||||
var demoRoot = server.Host.Config.Data.Root;
|
||||
try
|
||||
{
|
||||
var page = await server.TextAsync("/conti");
|
||||
|
||||
// Mockup 02: totals, the two cards, the stops. The ledger computes them from the seeded rows.
|
||||
foreach (var figure in new[]
|
||||
{
|
||||
"10.412,46", "6.671,13", "3.741,33", "4.231,60", "1.905,10", "2.326,50", "+163,45", "+68,15", "14,49",
|
||||
"6.180,86", "7.170,41", "1.836,23", "2.130,21", "4.344,63", "5.040,20", "+75,83", "+105,03", "0,33",
|
||||
"+231,60", "+5,79%", "+180,86", "+3,01%", "22,3%", "37,5%", "4,3%", "35,9%", "59,4%", "40,6%",
|
||||
})
|
||||
{
|
||||
StringAssert.Contains(page, figure, $"Missing {figure} on the Conti page.");
|
||||
}
|
||||
|
||||
StringAssert.Contains(page, "Attivo, aggiornato oggi alle 02:06");
|
||||
StringAssert.Contains(page, "Attivo dal 7 ottobre");
|
||||
StringAssert.Contains(page, "5 stop permanenti");
|
||||
StringAssert.Contains(page, "6 stop giornalieri");
|
||||
StringAssert.Contains(page, "In coda per l'apertura delle 15:30");
|
||||
StringAssert.Contains(page, "Registro interno coerente (controllo delle 08:20)");
|
||||
StringAssert.Contains(page, "i prelievi sono disattivati");
|
||||
StringAssert.Contains(page, "circa 309");
|
||||
Assert.IsLessThan(page.IndexOf("Vendi 0,262", StringComparison.Ordinal), page.IndexOf("Vendi 0,0182", StringComparison.Ordinal), "The largest stop comes first.");
|
||||
|
||||
// The filter keeps one account; the CSV has one row per position, for a spreadsheet.
|
||||
var okx = await server.TextAsync("/conti?conto=okx");
|
||||
Assert.IsFalse(okx.Contains("NVDA", StringComparison.Ordinal));
|
||||
using var csv = await server.GetAsync("/api/conti/posizioni.csv");
|
||||
Assert.AreEqual(HttpStatusCode.OK, csv.StatusCode);
|
||||
Assert.AreEqual("text/csv", csv.Content.Headers.ContentType?.MediaType);
|
||||
var bytes = await csv.Content.ReadAsByteArrayAsync();
|
||||
CollectionAssert.AreEqual(new byte[] { 0xEF, 0xBB, 0xBF }, bytes[..3], "Excel reads the accents only with the BOM.");
|
||||
var lines = System.Text.Encoding.UTF8.GetString(bytes[3..]).Split('\n', StringSplitOptions.RemoveEmptyEntries);
|
||||
Assert.HasCount(11, lines);
|
||||
StringAssert.StartsWith(lines[1], "BTC/EUR;Bitcoin;okx;crypto_trend;0.0182;68950;71420;EUR;1299.84;44.95;66180;", lines[1]);
|
||||
|
||||
var settings = await server.TextAsync("/impostazioni");
|
||||
StringAssert.Contains(settings, "Conti e chiavi");
|
||||
StringAssert.Contains(settings, "Nella modalità dimostrativa chiavi e capitale non si cambiano.");
|
||||
Assert.IsFalse(settings.Contains("/azioni/capitale/", StringComparison.Ordinal), "No capital form in the demo.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
TempFolder.Delete(demoRoot);
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Integration)]
|
||||
public async Task KeysAreAskedToTheBrokerBeforeTheyAreKept()
|
||||
{
|
||||
var network = new FakeHttp()
|
||||
.On(u => u.AbsolutePath == "/api/v5/account/config", _ => FakeHttp.Respond(Fixture.Text("okx-trading/account-config.json")))
|
||||
.On(u => u.AbsolutePath == "/v2/account", _ => FakeHttp.Respond(Fixture.Text("alpaca-trading/account.json")))
|
||||
.On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound));
|
||||
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network, trading: true);
|
||||
await server.SignInFirstTimeAsync();
|
||||
var secrets = server.Host.Services!.Secrets;
|
||||
|
||||
// The documentation's OKX key may withdraw: refused, nothing saved.
|
||||
using (var okx = await server.PostFormAsync("/impostazioni", "/azioni/chiavi/okx",
|
||||
("OKX_API_KEY_DEMO", "test-okx-key"), ("OKX_API_SECRET_DEMO", "test-okx-secret"), ("OKX_API_PASSPHRASE_DEMO", "test-okx-pass")))
|
||||
{
|
||||
Assert.AreEqual("/impostazioni?errore=prelievo#conti", ServerHarness.Location(okx));
|
||||
}
|
||||
|
||||
Assert.IsFalse((await secrets.StatusAsync("OKX_API_KEY_DEMO")).IsSet);
|
||||
|
||||
// A missing field never reaches the broker.
|
||||
using (var empty = await server.PostFormAsync("/impostazioni", "/azioni/chiavi/alpaca", ("ALPACA_API_KEY_DEMO", "test-alpaca-key"), ("ALPACA_API_SECRET_DEMO", " ")))
|
||||
{
|
||||
Assert.AreEqual("/impostazioni?errore=chiavi-vuote#conti", ServerHarness.Location(empty));
|
||||
}
|
||||
|
||||
// Alpaca keys never withdraw and this account may trade: kept, encrypted, never shown again; the engine restarts with them.
|
||||
using (var alpaca = await server.PostFormAsync("/impostazioni", "/azioni/chiavi/alpaca", ("ALPACA_API_KEY_DEMO", "test-alpaca-key"), ("ALPACA_API_SECRET_DEMO", "test-alpaca-secret")))
|
||||
{
|
||||
Assert.AreEqual("/impostazioni?ok=chiavi#conti", ServerHarness.Location(alpaca));
|
||||
}
|
||||
|
||||
await server.WaitForAsync(HostMode.Ready);
|
||||
secrets = server.Host.Services!.Secrets;
|
||||
Assert.IsTrue((await secrets.StatusAsync("ALPACA_API_SECRET_DEMO")).IsSet);
|
||||
var settings = await server.TextAsync("/impostazioni");
|
||||
Assert.IsFalse(settings.Contains("test-alpaca-secret", StringComparison.Ordinal), "A saved key is never shown again.");
|
||||
StringAssert.Contains(settings, "Impostata");
|
||||
// The engine starts in the background after "ready": the paper account appears within moments.
|
||||
var accounts = new List<string>();
|
||||
for (var i = 0; i < 100 && accounts.Count == 0; i++)
|
||||
{
|
||||
accounts = [.. await server.Host.Services.Db.ReadAsync(s => s.QueryAsync("SELECT name FROM accounts WHERE environment = 'demo'", r => r.Text("name")))];
|
||||
if (accounts.Count == 0)
|
||||
{
|
||||
await Task.Delay(100);
|
||||
}
|
||||
}
|
||||
|
||||
CollectionAssert.AreEqual(new[] { "Alpaca paper" }, accounts.ToArray());
|
||||
|
||||
// Capital in euro, as people type it; dollars need the ECB rate first.
|
||||
using (var capital = await server.PostFormAsync("/impostazioni", "/azioni/capitale/okx", ("euro", "1.500,50")))
|
||||
{
|
||||
Assert.AreEqual("/impostazioni?ok=capitale#conti", ServerHarness.Location(capital));
|
||||
}
|
||||
|
||||
using (var usd = await server.PostFormAsync("/impostazioni", "/azioni/capitale/alpaca", ("euro", "2000")))
|
||||
{
|
||||
Assert.AreEqual("/impostazioni?errore=cambio#conti", ServerHarness.Location(usd));
|
||||
}
|
||||
|
||||
using (var bad = await server.PostFormAsync("/impostazioni", "/azioni/capitale/okx", ("euro", "molto")))
|
||||
{
|
||||
Assert.AreEqual("/impostazioni?errore=importo#conti", ServerHarness.Location(bad));
|
||||
}
|
||||
|
||||
var changes = await server.Host.Services.Db.ReadAsync(s => s.QueryAsync("SELECT broker, amount_eur FROM capital_changes", r => (r.Text("broker"), r.Money("amount_eur"))));
|
||||
CollectionAssert.AreEqual(new[] { ("okx", 1500.50m) }, changes.ToArray());
|
||||
StringAssert.Contains(await server.TextAsync("/impostazioni"), "Trend crypto: quota 100%");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[TestCategory(Category.Unit)]
|
||||
[DataRow("4000", "4000")]
|
||||
[DataRow("1.500", "1500")]
|
||||
[DataRow("1.500,50", "1500.50")]
|
||||
[DataRow("1500,5", "1500.5")]
|
||||
[DataRow("1500.50", "1500.50")]
|
||||
[DataRow(" 2 000 € ", "2000")]
|
||||
[DataRow("10,999", "10.99")]
|
||||
[DataRow("-5", null)]
|
||||
[DataRow("abc", null)]
|
||||
[DataRow("", null)]
|
||||
public void AmountsAreReadAsPeopleTypeThem(string text, string? expected) =>
|
||||
Assert.AreEqual(expected is null ? null : decimal.Parse(expected, System.Globalization.CultureInfo.InvariantCulture), Forms.ParseEuro(text));
|
||||
}
|
||||
@@ -76,7 +76,7 @@ internal sealed partial class ServerHarness : IAsyncDisposable
|
||||
}
|
||||
|
||||
public static async Task<ServerHarness> StartAsync(string platform, IReadOnlyDictionary<string, string?> environment, string? dataDir = null,
|
||||
string[]? extraArgs = null, bool waitReady = true, HttpMessageHandler? marketHttp = null)
|
||||
string[]? extraArgs = null, bool waitReady = true, HttpMessageHandler? marketHttp = null, bool trading = false)
|
||||
{
|
||||
var owns = dataDir is null;
|
||||
dataDir ??= TempFolder.Create("server");
|
||||
@@ -89,6 +89,7 @@ internal sealed partial class ServerHarness : IAsyncDisposable
|
||||
MarketData = marketHttp is not null,
|
||||
MarketHttp = marketHttp,
|
||||
MarketSockets = marketHttp is null ? null : () => new FakeSocket(),
|
||||
Trading = trading,
|
||||
});
|
||||
await app.StartAsync().ConfigureAwait(false);
|
||||
var cookies = new CookieContainer();
|
||||
|
||||
@@ -135,7 +135,7 @@ int Screenshots(string[] pages)
|
||||
|
||||
var folder = Path.Combine(root, "artifacts", "screenshots");
|
||||
Directory.CreateDirectory(folder);
|
||||
var targets = pages.Length > 0 ? pages : ["/", "/diario", "/impostazioni"];
|
||||
var targets = pages.Length > 0 ? pages : ["/", "/conti", "/diario", "/impostazioni"];
|
||||
using var shots = Shots.Start(browser);
|
||||
foreach (var page in targets)
|
||||
{
|
||||
|
||||
@@ -96,6 +96,22 @@ internal sealed class Shots : IDisposable
|
||||
});
|
||||
Send("Page.navigate", new JsonObject { ["url"] = url }, waitForEvent: "Page.loadEventFired");
|
||||
Thread.Sleep(500);
|
||||
|
||||
// The whole page, not just the first screen: a page taller than the window grows the window to fit.
|
||||
var metrics = Send("Page.getLayoutMetrics", new JsonObject());
|
||||
var full = (int)Math.Ceiling(metrics["cssContentSize"]?["height"]?.GetValue<double>() ?? height);
|
||||
if (full > height)
|
||||
{
|
||||
Send("Emulation.setDeviceMetricsOverride", new JsonObject
|
||||
{
|
||||
["width"] = width,
|
||||
["height"] = full,
|
||||
["deviceScaleFactor"] = 2,
|
||||
["mobile"] = width < 768,
|
||||
});
|
||||
Thread.Sleep(300);
|
||||
}
|
||||
|
||||
var result = Send("Page.captureScreenshot", new JsonObject { ["format"] = "png" });
|
||||
File.WriteAllBytes(file, Convert.FromBase64String(result["data"]!.GetValue<string>()));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user