Files
Anubis/src/Anubis.Server/ReasonTexts.cs
T
Alby96andClaude Opus 5.5 13f9c42f61 Add the Operazioni, Strategie and Rischio screens (refs #45)
The three screens follow mockups 03, 04 and 07.

Operazioni shows the balance of the closed trades, filters, a CSV export,
and for each trade why it was bought and sold. The reasons come from the
decision codes through fixed Italian templates.

Strategie shows the four stages towards real money, a card per strategy
with its requirements, the procedure of SPEC 12.4, and why each strategy in
observation waits. A strategy that failed its backtest cannot be moved into
the simulation.

Rischio shows the emergency switch, the automatic blocks, the use of each
limit, the fall from the peak, the scenarios and the risk events. Stop,
close and restart now go through the risk engine. A restart is refused
while the STOP file exists.

Impostazioni gains the limits, the day-trade guard and the scenarios.
Lowering a limit is always allowed. Raising a limit or the entrusted capital
while a strategy uses real money needs the phrase and the password.

The demo now holds the decisions behind its trades, the 58 days of
simulation and the indices of its curves, so it matches the mockups.

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

125 lines
7.4 KiB
C#

using System.Globalization;
using System.Text.Json;
using Anubis.Core;
using Anubis.Trading;
namespace Anubis.Server;
/// <summary>
/// The fixed templates that turn the reason codes of the decisions table into plain Italian (SPEC 5.2): the "why"
/// card of a trade and the diary use these, never free text written at decision time. An unknown code is shown as
/// it is, so nothing is ever hidden.
/// </summary>
internal static class ReasonTexts
{
private static readonly Dictionary<string, string> Texts = new(StringComparer.Ordinal)
{
// Strategies.
["trend_entry"] = "La chiusura ha superato i massimi recenti su almeno un orizzonte: è iniziata una tendenza al rialzo.",
["trend_increase"] = "Più orizzonti erano d'accordo sulla tendenza: il peso è salito.",
["trend_reduce"] = "La tendenza si è indebolita, o la moneta è diventata più agitata: il peso è sceso.",
["trend_exit"] = "La tendenza si è interrotta: il prezzo è finito sotto lo stop mobile.",
["trend_stop"] = "Lo stop mobile è salito con il prezzo.",
["momentum_entry"] = "Era tra i titoli più forti degli ultimi mesi, con il mercato in salita.",
["momentum_increase"] = "Il peso obiettivo è salito alla revisione settimanale.",
["momentum_reduce"] = "Il peso obiettivo è sceso alla revisione settimanale.",
["momentum_exit_rank"] = "Non era più tra i 30 titoli più forti.",
["momentum_exit_trend"] = "Il mercato nel suo insieme è girato al ribasso: niente più azioni.",
["momentum_stop"] = "Lo stop di protezione è stato aggiornato.",
["meanrev_entry"] = "Era sceso per qualche seduta di fila ma restava sopra la sua media a 200 giorni: un ribasso breve di un titolo che nel lungo periodo sale.",
["meanrev_exit_average"] = "Il prezzo è tornato sopra la media a 5 giorni: il rimbalzo cercato è arrivato.",
["meanrev_exit_rsi"] = "L'indicatore di forza è tornato alto: il rimbalzo è avvenuto.",
["meanrev_exit_earnings"] = "Uscita prima della trimestrale.",
["meanrev_exit_time"] = "Tempo scaduto: nessun rimbalzo in 5 sedute.",
// Exits recorded on the trade.
["stop"] = "Stop di protezione raggiunto.",
["exit"] = "Uscita decisa dalla strategia.",
["signal"] = "Uscita sul segnale della strategia.",
["residue"] = "Resto troppo piccolo per essere venduto, tolto dal registro.",
["adjustment"] = "Rettifica dopo l'allineamento con il conto.",
// Correctives.
["crypto_regime_below_average"] = "Il mercato crypto era sotto la sua media: acquisti ridotti.",
["crypto_regime_high_volatility"] = "Il mercato crypto era molto agitato: acquisti ridotti.",
["calendar_event"] = "Un dato economico importante era vicino: niente nuove posizioni in quell'ora.",
// Risk.
["risk_reduction"] = "Ordine rimpicciolito dai limiti di rischio.",
["daily_loss_block"] = "Perdita del giorno oltre il limite: niente nuovi ingressi per 24 ore.",
["switch_tripped"] = "Interruttore scattato: il bot aspetta la tua conferma.",
["bot_paused"] = "Bot in pausa: niente nuovi ingressi.",
["bot_stopped"] = "Bot fermato con \"Ferma tutto\".",
["invested_limit"] = "Capitale investito al limite: niente soldi presi in prestito.",
["position_limit"] = "Ridotto al peso massimo di una posizione.",
["crypto_limit"] = "Quota delle crypto sul totale al limite.",
["trade_risk_limit"] = "Ridotto perché il rischio dell'operazione restasse entro il limite.",
["stop_above_price"] = "Stop sopra il prezzo: ordine rifiutato.",
["stale_price"] = "Prezzo troppo vecchio: niente acquisti finché i dati non tornano freschi.",
["price_gap"] = "Prezzo dell'ordine troppo lontano dall'ultimo prezzo.",
["clock_skew"] = "Orologio non allineato con quello del broker.",
["owned_by_other_strategy"] = "La posizione appartiene a un'altra strategia.",
["no_short_selling"] = "Niente vendite allo scoperto: venduto solo quanto posseduto.",
["no_leverage"] = "Niente leva: l'ordine sta nella liquidità disponibile.",
["not_owned_by_bot"] = "La posizione non è del bot: non la tocca.",
["live_not_confirmed"] = "Soldi veri non confermati per questa strategia.",
["exit_only"] = "Strategia in sola uscita: niente nuovi acquisti.",
["live_not_allowed"] = "Soldi veri non permessi dalla configurazione d'avvio.",
["observation"] = "Strategia in osservazione: produce segnali, nessun ordine.",
["orders_per_minute"] = "Troppi ordini in un minuto: il bot si è fermato.",
["pdt_guard"] = "Guardia sulle operazioni in giornata: niente posizioni in più oggi.",
["no_fx_rate"] = "Manca il cambio euro-dollaro: niente acquisti in dollari.",
["unknown_instrument"] = "Strumento sconosciuto.",
};
// The exits in the few words of a table column; the full sentence stays for the "why" card.
private static readonly Dictionary<string, string> ShortExits = new(StringComparer.Ordinal)
{
["trend_exit"] = "La tendenza si è interrotta: prezzo sotto lo stop mobile",
["momentum_exit_rank"] = "Non era più tra i 30 titoli più forti",
["momentum_exit_trend"] = "Il mercato è girato al ribasso",
["meanrev_exit_average"] = "Tornata sopra la media a 5 giorni",
["meanrev_exit_rsi"] = "Rimbalzo arrivato: forza tornata alta",
["meanrev_exit_earnings"] = "Uscita prima della trimestrale",
["meanrev_exit_time"] = "Tempo scaduto: nessun rimbalzo in 5 sedute",
["stop"] = "Stop di protezione raggiunto",
};
/// <summary>Why a trade was closed, in a short sentence.</summary>
public static string Exit(string? code) => code is null ? "Chiusa" : ShortExits.TryGetValue(code, out var text) ? text : Text(code).TrimEnd('.');
public static string Text(string code) => Texts.TryGetValue(code, out var text) ? text : code;
/// <summary>The lines of one stage of a decision. <paramref name="data"/> is the JSON of the numbers the stage used.</summary>
public static IEnumerable<WhyLine> Stage(string stage, string outcome, IReadOnlyList<string> reasons, string? data)
{
ArgumentNullException.ThrowIfNull(reasons);
var good = outcome is DecisionOutcomes.Passed or DecisionOutcomes.Proposed or DecisionOutcomes.Same;
if (stage == DecisionStages.Risk && outcome == DecisionOutcomes.Passed && reasons.Count == 0)
{
yield return new WhyLine("Tutti i limiti di rischio rispettati" + Asked(data), true);
yield break;
}
foreach (var reason in reasons)
{
yield return new WhyLine(Text(reason).TrimEnd('.') + (stage == DecisionStages.Risk ? Asked(data) : ""), good || stage == DecisionStages.Strategy);
}
}
// "(chiesti 0,05, passati 0,03)" when the stage shrank the order.
private static string Asked(string? data)
{
if (data is null)
{
return "";
}
using var json = JsonDocument.Parse(data);
if (json.RootElement.TryGetProperty("asked", out var asked) && json.RootElement.TryGetProperty("allowed", out var allowed) &&
asked.TryGetDecimal(out var a) && allowed.TryGetDecimal(out var b) && b < a)
{
return $" (chiesti {Format.Quantity(a)}, passati {Format.Quantity(b)})";
}
return "";
}
}