using System.Text; using Anubis.Core; using Anubis.Data; using Anubis.Notifications; using Anubis.Trading; namespace Anubis.Server; /// /// The answers of the Telegram commands and the messages the bot writes by itself (SPEC 14), from the same data as /// the Panoramica: one world, the simulated one until there is a real account. /// internal sealed class TelegramDesk(AnubisHost host) : ITelegramDesk { private const string By = "Telegram"; private AppServices Services => host.Services ?? throw new InvalidOperationException("Il bot sta ancora partendo: riprova tra poco."); private TimeZoneInfo Zone => host.Config.TimeZone; public async Task StatusAsync(CancellationToken cancellationToken) { var services = Services; var now = host.Clock.UtcNow; var bot = (await services.Settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value; var overview = await Overview.LoadAsync(services, "oggi", now, Zone, cancellationToken).ConfigureAwait(false); var text = new StringBuilder(); text.Append(bot switch { "paused" => "Bot in pausa", "stopped" => "Bot fermo («Ferma tutto»)", _ => "Bot attivo" }) .Append(" · solo denaro finto").AppendLine("."); if (overview.HasData) { var today = overview.Cells[0]; text.Append("Patrimonio ").Append(Format.Money(overview.Points[^1].Equity)).Append(", oggi ").Append(Format.Money(today.Amount, withSign: true)) .Append(" (").Append(Format.Percent(today.Percent, 2, withSign: true)).AppendLine(")."); } text.Append(Positions(overview.Positions, overview.PositionsWithoutStop)); if (overview.OpenOrders > 0) { text.Append(' ').Append(overview.OpenOrders == 1 ? "1 ordine in corso." : $"{overview.OpenOrders} ordini in corso."); } text.AppendLine(); if (overview.Next.Count > 0 && overview.Next[0] is var next) { text.Append("Prossima mossa: ").Append(next.Time).Append(' ').Append(next.Text).AppendLine("."); } return text.ToString().TrimEnd(); } public async Task PositionsAsync(CancellationToken cancellationToken) { var services = Services; var rows = await services.Db.ReadAsync(s => s.QueryAsync( "SELECT a.name, a.environment, a.base_currency, i.symbol, p.strategy, p.quantity, p.average_price, p.last_price, p.stop_price FROM positions p " + "JOIN accounts a ON a.id = p.account_id JOIN instruments i ON i.id = p.instrument_id WHERE p.quantity > 0 ORDER BY a.name, i.symbol", r => (Account: r.Text("name"), Environment: r.Text("environment"), Currency: r.Text("base_currency"), Symbol: r.Text("symbol"), Strategy: r.Text("strategy"), Quantity: r.Money("quantity"), Average: r.Money("average_price"), Last: r.MoneyOrNull("last_price"), Stop: r.MoneyOrNull("stop_price"))), cancellationToken) .ConfigureAwait(false); var world = rows.Any(r => TradingEnvironments.World(r.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated; rows = [.. rows.Where(r => TradingEnvironments.World(r.Environment) == world)]; if (rows.Count == 0) { return "Nessuna posizione aperta."; } var text = new StringBuilder(); foreach (var r in rows) { var last = r.Last ?? r.Average; var gain = (last - r.Average) * r.Quantity; text.Append(DiaryText.Shown(r.Symbol)).Append(": ").Append(Format.Quantity(r.Quantity)).Append(" a ").Append(Format.Money(r.Average, r.Currency)) .Append(", ora ").Append(Format.Money(last, r.Currency)).Append(" (").Append(Format.Money(gain, r.Currency, withSign: true)).Append("), ") .Append(r.Stop is { } stop ? "stop a " + Format.Money(stop, r.Currency) : "SENZA STOP") .Append(" · ").Append(StrategyNames.Label(r.Strategy)).Append(", ").Append(r.Account).AppendLine(); } return text.ToString().TrimEnd(); } public async Task TodayAsync(CancellationToken cancellationToken) { var services = Services; var now = host.Clock.UtcNow; var local = TimeZoneInfo.ConvertTime(now, Zone); var midnight = new DateTimeOffset(local.Date, local.Offset).ToUniversalTime(); var entries = await services.Db.ReadAsync(s => s.QueryAsync( "SELECT occurred_at, message FROM journal WHERE kind = @k AND occurred_at >= @from ORDER BY occurred_at", r => (At: r.Moment("occurred_at"), Text: r.Text("message")), ("k", DiaryKinds.Orders), ("from", midnight)), cancellationToken).ConfigureAwait(false); var overview = await Overview.LoadAsync(services, "oggi", now, Zone, cancellationToken).ConfigureAwait(false); var text = new StringBuilder(); if (overview.HasData) { text.Append("Oggi ").Append(Format.Money(overview.Cells[0].Amount, withSign: true)).Append(" (").Append(Format.Percent(overview.Cells[0].Percent, 2, withSign: true)) .AppendLine(")."); } if (entries.Count == 0) { text.Append("Nessun ordine oggi."); return text.ToString(); } const int Shown = 15; foreach (var e in entries.TakeLast(Shown)) { text.Append(TimeZoneInfo.ConvertTime(e.At, Zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture)).Append(' ').AppendLine(e.Text); } if (entries.Count > Shown) { text.Append("…e altre ").Append(entries.Count - Shown).Append(" righe nel Diario."); } return text.ToString().TrimEnd(); } public Task PauseAsync(CancellationToken cancellationToken) => CommandAsync("pausa", "In pausa: niente nuovi acquisti; stop e uscite proseguono. /riprendi per ripartire.", cancellationToken); public Task ResumeAsync(CancellationToken cancellationToken) => CommandAsync("riprendi", "Ripartito dalla pausa.", cancellationToken); public Task StopAllAsync(CancellationToken cancellationToken) => CommandAsync("ferma", "«Ferma tutto» fatto: ordini in attesa annullati, niente nuove posizioni, gli stop restano. Si riparte solo dall'interfaccia, pagina Rischio.", cancellationToken); /// The morning summary (SPEC 14): the night, the positions, what comes today. public async Task MorningAsync(CancellationToken cancellationToken) { var services = Services; var now = host.Clock.UtcNow; var overview = await Overview.LoadAsync(services, "oggi", now, Zone, cancellationToken).ConfigureAwait(false); var text = new StringBuilder("Buongiorno.").AppendLine(); if (overview.HasData) { text.Append("Patrimonio ").Append(Format.Money(overview.Points[^1].Equity)).Append("; ultimi 7 giorni ").Append(Format.Money(overview.Cells[1].Amount, withSign: true)) .AppendLine("."); } text.AppendLine(Positions(overview.Positions, overview.PositionsWithoutStop)); var local = TimeZoneInfo.ConvertTime(now, Zone).Date; var today = overview.Next.Count == 0 ? [] : services.Scheduler.Upcoming(200) .Where(u => u.IsMove && TimeZoneInfo.ConvertTime(u.DueUtc, Zone).Date == local) .Select(u => TimeZoneInfo.ConvertTime(u.DueUtc, Zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture) + " " + u.Description) .ToList(); if (today.Count > 0) { text.AppendLine("Oggi:"); foreach (var line in today) { text.AppendLine(line); } } return text.ToString().TrimEnd(); } private static string Positions(int count, int withoutStop) => count switch { 0 => "Nessuna posizione aperta.", 1 => withoutStop == 0 ? "1 posizione, con il suo stop." : "1 posizione, SENZA STOP.", _ => withoutStop == 0 ? $"{count} posizioni, tutte con lo stop." : $"{count} posizioni, {withoutStop} SENZA STOP.", }; private async Task CommandAsync(string command, string done, CancellationToken cancellationToken) { if (host.IsDemo) { return "Nella modalità dimostrativa il bot non si comanda."; } var (ok, message) = await Endpoints.BotCommandAsync(host, command, By, cancellationToken).ConfigureAwait(false); return ok ? done : message; } }