using System.Globalization;
using System.Text;
using Anubis.Core;
using Anubis.Data;
using Anubis.Db;
using Anubis.Trading;
namespace Anubis.Server;
/// One account of the Conti screen, in its own currency and in euro.
internal sealed record AccountCard(Guid Id, string Name, string Broker, string Environment, string Currency, decimal Cash, decimal Invested, decimal InvestedEur, int Holdings,
decimal Realized, decimal Unrealized, decimal Fees, decimal Flows, AccountState State, decimal Rate)
{
/// Cash plus the positions, each valued to the cent as the table shows it, so the figures add up on screen.
public decimal Equity => Cash + Invested;
public string Kind => Broker == Venues.Alpaca ? "Azioni USA" : "Crypto";
public string Short => Broker == Venues.Alpaca ? "Alpaca" : "OKX";
public decimal Result => Equity - Flows;
public decimal Percent => Flows > 0m ? Result / Flows * 100m : 0m;
/// An amount of this account in euro, at the latest rate.
public decimal Eur(decimal amount) => Currency == "EUR" || Rate <= 0m ? amount : amount / Rate;
}
internal sealed record PositionRow(Guid AccountId, string Broker, string Symbol, string Name, string Strategy, decimal Quantity, decimal Average, decimal Last, decimal? Stop,
string Currency, DateTimeOffset OpenedAt, decimal ValueEur, decimal ResultEur)
{
public decimal Percent => Average == 0m ? 0m : (Last / Average - 1m) * 100m;
}
/// A line of "Ordini in attesa": one order, or the stops of Alpaca grouped by validity.
internal sealed record PendingRow(string Action, string Subject, string Where, string Level, string Status, bool Waiting);
internal sealed record ResidueRow(string Broker, string Symbol, decimal Quantity, decimal Value, string Currency, DateTimeOffset At);
internal sealed record StrategySlice(string Label, string Color, decimal Eur);
///
/// The Conti e posizioni screen (SPEC 13.6, mockup 02): totals, accounts with key and reconciliation, open positions,
/// pending orders, residues and where the money is by currency. One world only: real accounts when there are any,
/// otherwise the simulated ones, so finto and vero never add up (SPEC 7.1).
///
internal sealed record AccountsView(
IReadOnlyList Accounts,
IReadOnlyList Positions,
IReadOnlyList Pending,
int PendingOthers,
bool AlpacaStops,
IReadOnlyList Residues,
IReadOnlyList Slices,
decimal? UsdRate,
DateOnly? RateDay,
decimal? FxEffect,
bool MarketOpen,
DateTimeOffset MarketNext)
{
public bool HasAccounts => Accounts.Count > 0;
public decimal TotalEur => Accounts.Sum(a => a.Eur(a.Equity));
public decimal CashEur => Accounts.Sum(a => a.Eur(a.Cash));
public decimal InvestedEur => Accounts.Sum(a => a.InvestedEur);
public decimal ResultEur => Accounts.Sum(a => a.Eur(a.Result));
public decimal OpenResultEur => Positions.Sum(p => p.ResultEur);
public static async Task LoadAsync(AppServices services, IClock clock, TimeZoneInfo zone, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(services);
var ledger = services.Trading?.Ledger ?? new Ledger(services.Db, clock);
var reconciler = services.Trading?.Reconciler ?? new Reconciler(services.Db, clock, ledger);
var fx = await new FxStore(services.Db, clock).LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false);
var rate = fx?.Rate ?? 0m;
var (accounts, instruments, trades, orders, residues) = await services.Db.ReadAsync(async s =>
{
var a = await s.QueryAsync("SELECT id, name, broker, environment, base_currency FROM accounts ORDER BY broker DESC, created_at",
r => (Id: r.Id("id"), Name: r.Text("name"), Broker: r.Text("broker"), Environment: r.Text("environment"), Currency: r.Text("base_currency"))).ConfigureAwait(false);
var i = await s.QueryAsync("SELECT id, symbol, name, quote_currency FROM instruments",
r => (Id: r.Id("id"), Symbol: r.Text("symbol"), Name: r.TextOrNull("name"), Quote: r.TextOrNull("quote_currency"))).ConfigureAwait(false);
var t = await s.QueryAsync("SELECT account_id, realized, fees FROM trades", r => (Account: r.Id("account_id"), Realized: r.Money("realized"), Fees: r.Money("fees")))
.ConfigureAwait(false);
var o = await s.QueryAsync(
"SELECT account_id, instrument_id, side, order_type, purpose, quantity, filled_quantity, limit_price, stop_price, time_in_force, step, created_at, updated_at FROM orders " +
"WHERE status IN ('created', 'submitted', 'partially_filled') ORDER BY created_at, id",
r => new OpenOrder(r.Id("account_id"), r.Id("instrument_id"), r.Text("side"), r.Text("order_type"), r.TextOrNull("purpose") ?? "entry", r.Money("quantity"),
r.MoneyOrNull("filled_quantity") ?? 0m, r.MoneyOrNull("limit_price"), r.MoneyOrNull("stop_price"), r.TextOrNull("time_in_force") ?? "day",
r.IsNull("step") ? null : (int)r.Number("step"), r.Moment("created_at"), r.Moment("updated_at"))).ConfigureAwait(false);
var res = await s.QueryAsync("SELECT account_id, instrument_id, quantity, value, currency, created_at FROM residues ORDER BY created_at DESC",
r => (Account: r.Id("account_id"), Instrument: r.Id("instrument_id"), Quantity: r.Money("quantity"), Value: r.Money("value"), Currency: r.Text("currency"),
At: r.Moment("created_at"))).ConfigureAwait(false);
return (a, i.ToDictionary(x => x.Id), t, o, res);
}, cancellationToken).ConfigureAwait(false);
var world = accounts.Any(a => TradingEnvironments.World(a.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated;
accounts = accounts.Where(a => TradingEnvironments.World(a.Environment) == world).ToList();
var shown = accounts.Select(a => a.Id).ToHashSet();
var equities = (await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false)).Where(e => shown.Contains(e.AccountId)).ToList();
var positions = (await ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false)).Where(p => shown.Contains(p.AccountId)).ToList();
var rates = accounts.ToDictionary(a => a.Id, a => a.Currency == "USD" ? rate : 1m);
decimal Eur(Guid account, decimal amount) => rates[account] is var r && r > 0m && r != 1m ? amount / r : amount;
var currencies = accounts.ToDictionary(a => a.Id, a => a.Currency);
var rows = positions
.Select(p =>
{
var instrument = instruments.GetValueOrDefault(p.InstrumentId);
var value = Math.Round(p.Value, 2, MidpointRounding.AwayFromZero);
return (Native: value, Row: new PositionRow(p.AccountId, accounts.First(a => a.Id == p.AccountId).Broker, instrument.Symbol ?? "?", instrument.Name ?? "", p.Strategy,
p.Quantity, p.AveragePrice, p.LastPrice ?? p.AveragePrice, p.StopPrice, instrument.Quote ?? currencies[p.AccountId], p.OpenedAt,
Math.Round(Eur(p.AccountId, value), 2, MidpointRounding.AwayFromZero), Math.Round(Eur(p.AccountId, p.Unrealized), 2, MidpointRounding.AwayFromZero)));
})
.OrderByDescending(r => r.Row.ValueEur)
.ToList();
var cards = new List();
foreach (var a in accounts)
{
var mine = equities.Where(e => e.AccountId == a.Id).ToList();
var held = positions.Where(p => p.AccountId == a.Id).ToList();
var valued = rows.Where(r => r.Row.AccountId == a.Id).ToList();
var state = await reconciler.StateAsync(a.Id, cancellationToken).ConfigureAwait(false);
cards.Add(new AccountCard(a.Id, a.Name, a.Broker, a.Environment, a.Currency, mine.Sum(e => e.Cash), valued.Sum(r => r.Native), valued.Sum(r => r.Row.ValueEur),
held.Select(p => p.InstrumentId).Distinct().Count(), trades.Where(t => t.Account == a.Id).Sum(t => t.Realized), held.Sum(p => p.Unrealized),
trades.Where(t => t.Account == a.Id).Sum(t => t.Fees), mine.Sum(e => e.Flows), state, rates[a.Id]));
}
var byId = cards.ToDictionary(c => c.Id);
var market = MarketState(services.MarketData?.UsCalendar, clock.UtcNow);
var (pending, others, alpacaStops) = PendingRows(orders.Where(o => shown.Contains(o.Account)).ToList(), byId, instruments.ToDictionary(i => i.Key, i => i.Value.Symbol),
positions, market.Open, market.Next, clock.UtcNow, zone);
var slices = StrategyNames.Base.Select(b => new StrategySlice(StrategyNames.Label(b.Name, withMarket: true), "var(--s-" + b.Name.Replace('_', '-') + ")",
rows.Where(r => r.Row.Strategy == b.Name).Sum(r => r.Row.ValueEur))).ToList();
decimal? fxEffect = null;
if (cards.Count > 0)
{
fxEffect = await services.Db.ReadAsync(s => s.FirstOrDefaultAsync(
"SELECT fx_effect FROM equity_snapshots WHERE scope = 'total' AND world = @w ORDER BY taken_at DESC LIMIT 1", r => r.MoneyOrNull("fx_effect"), ("w", world)),
cancellationToken).ConfigureAwait(false);
}
var residueRows = residues.Where(r => shown.Contains(r.Account))
.Select(r => new ResidueRow(byId[r.Account].Short, instruments.GetValueOrDefault(r.Instrument).Symbol ?? "?", r.Quantity, r.Value, r.Currency, r.At)).ToList();
return new AccountsView(cards, rows.Select(r => r.Row).ToList(), pending, others, alpacaStops, residueRows, slices, fx?.Rate, fx?.Date, fxEffect, market.Open, market.Next);
}
/// The positions as CSV for an Italian spreadsheet (SPEC 13): semicolons, decimal commas, no thousands separator, one row per position.
public string Csv(string? broker)
{
var text = new StringBuilder("strumento;nome;conto;strategia;quantita;prezzo_medio;prezzo_ora;valuta;valore_eur;risultato_eur;stop;aperta_il\n");
foreach (var p in Positions.Where(p => broker is null || p.Broker == broker))
{
text.Append(string.Join(';', Clean(p.Symbol), Clean(p.Name), p.Broker, p.Strategy, Number(p.Quantity), Number(p.Average), Number(p.Last), p.Currency,
Number(Math.Round(p.ValueEur, 2)), Number(Math.Round(p.ResultEur, 2)), p.Stop is { } stop ? Number(stop) : "",
p.OpenedAt.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture))).Append('\n');
}
return text.ToString();
// Trailing zeros dropped, so both database engines give the same text.
static string Number(decimal value) => (value / 1.000000000000000000000000000000000m).ToString(CultureInfo.InvariantCulture).Replace('.', ',');
static string Clean(string value) => Format.CsvText(value);
}
private sealed record OpenOrder(Guid Account, Guid Instrument, string Side, string Kind, string Purpose, decimal Quantity, decimal Filled, decimal? Limit, decimal? Stop,
string Tif, int? Step, DateTimeOffset CreatedAt, DateTimeOffset UpdatedAt);
private static (List Rows, int Others, bool AlpacaStops) PendingRows(List orders, Dictionary accounts, Dictionary symbols,
IReadOnlyList positions, bool marketOpen, DateTimeOffset marketNext, DateTimeOffset now, TimeZoneInfo zone)
{
var rows = new List();
var others = 0;
foreach (var o in orders.Where(o => o.Purpose != "stop"))
{
others++;
var account = accounts[o.Account];
var verb = o.Side == "buy" ? "Compra" : "Vendi";
var level = o.Limit is { } limit ? Format.Money(limit, account.Currency) : "a mercato";
var status = o.Step is { } step && o.Kind == "limit" ? $"Passo {Math.Min(step + 1, 4)} di 4, dalle {Local(o.CreatedAt, zone)}" : "In corso dalle " + Local(o.CreatedAt, zone);
rows.Add(new PendingRow($"{verb} {Format.Quantity(o.Quantity - o.Filled)}", symbols.GetValueOrDefault(o.Instrument) ?? "?", account.Short, level, status, false));
}
var stops = orders.Where(o => o.Purpose == "stop").ToList();
foreach (var o in stops.Where(o => accounts[o.Account].Broker != Venues.Alpaca).OrderByDescending(o => (o.Quantity - o.Filled) * (o.Stop ?? 0m)))
{
var account = accounts[o.Account];
var local = TimeZoneInfo.ConvertTime(o.UpdatedAt, zone);
var status = local.Date == TimeZoneInfo.ConvertTime(now, zone).Date && o.UpdatedAt > o.CreatedAt
? "Attivo, aggiornato oggi alle " + local.ToString("HH:mm", CultureInfo.InvariantCulture)
: "Attivo dal " + DayMonth(TimeZoneInfo.ConvertTime(o.CreatedAt, zone));
rows.Add(new PendingRow("Vendi " + Format.Quantity(o.Quantity - o.Filled), symbols.GetValueOrDefault(o.Instrument) ?? "?", account.Short,
o.Stop is { } stop ? Format.Money(stop, account.Currency, decimals: StopDecimals(stop)) : "", status, false));
}
var alpaca = stops.Where(o => accounts[o.Account].Broker == Venues.Alpaca).ToList();
var alpacaHeld = positions.Where(p => accounts.TryGetValue(p.AccountId, out var a) && a.Broker == Venues.Alpaca && p.StopPrice is not null).ToList();
var gtc = alpaca.Count(o => o.Tif == "gtc");
var fractions = alpacaHeld.Count(p => p.Quantity != decimal.Truncate(p.Quantity));
if (gtc > 0)
{
rows.Add(new PendingRow(gtc == 1 ? "1 stop permanente" : $"{gtc} stop permanenti", "sulle azioni intere", "Alpaca", "vedi tabella sopra", gtc == 1 ? "Attivo" : "Attivi", false));
}
if (fractions > 0)
{
var opens = Local(marketNext, zone);
rows.Add(new PendingRow(fractions == 1 ? "1 stop giornaliero" : $"{fractions} stop giornalieri", "sulle frazioni di azione", "Alpaca", "vedi tabella sopra",
marketOpen ? "Attivi fino alla chiusura delle " + opens : "In coda per l'apertura delle " + opens, !marketOpen));
}
return (rows, others, gtc > 0 || fractions > 0);
}
/// Whether the US market is open now, and its next close (open) or next open (closed).
public static (bool Open, DateTimeOffset Next) MarketState(IMarketCalendar? calendar, DateTimeOffset now)
{
var today = DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(now, Zones.NewYork).DateTime);
foreach (var useCalendar in new[] { true, false })
{
for (var d = -1; d <= 8; d++)
{
var day = today.AddDays(d);
var session = useCalendar ? calendar?.SessionOn(day) : Regular(day);
if (session is null)
{
continue;
}
if (now >= session.OpenUtc && now < session.CloseUtc)
{
return (true, session.CloseUtc);
}
if (session.OpenUtc > now)
{
return (false, session.OpenUtc);
}
}
}
return (false, now);
}
/// A regular session, 9:30 to 16:00 in New York on weekdays: used only when the broker's calendar is not there yet.
private static MarketSession? Regular(DateOnly day)
{
if (day.DayOfWeek is DayOfWeek.Saturday or DayOfWeek.Sunday)
{
return null;
}
DateTimeOffset At(int hour, int minute)
{
var local = day.ToDateTime(new TimeOnly(hour, minute));
return new DateTimeOffset(local, Zones.NewYork.GetUtcOffset(local)).ToUniversalTime();
}
return new MarketSession(day, At(9, 30), At(16, 0));
}
private static string Local(DateTimeOffset moment, TimeZoneInfo zone) => TimeZoneInfo.ConvertTime(moment, zone).ToString("HH:mm", CultureInfo.InvariantCulture);
/// Stops of a thousand or more without cents when they are round (66.180 €), the others with cents (166,00 $).
public static int StopDecimals(decimal stop) => stop >= 1000m && stop == decimal.Truncate(stop) ? 0 : 2;
public static string DayMonth(DateTimeOffset local)
{
var text = Format.LongDate(DateOnly.FromDateTime(local.DateTime));
return text[..text.LastIndexOf(' ')];
}
}