diff --git a/Encelado/CHANGELOG.md b/Encelado/CHANGELOG.md index a1380bb..5194035 100644 --- a/Encelado/CHANGELOG.md +++ b/Encelado/CHANGELOG.md @@ -4,11 +4,11 @@ Formato: una voce per sessione di lavoro, con data. Le voci più recenti in alto ## 2026-09-30/10-01 — 5.1.0: tutto dall'interfaccia, una sola password nel container, P&L oggi corretto, nuova interfaccia in stile Mimante -Le richieste dell'utente (`Modifiche.txt` del 2026-09-30), poi una revisione completa del codice con le correzioni. Versione di sviluppo 5.1.0 (`Directory.Build.props`, D-50); 532 test verdi, compilazione senza avvisi. Le scelte fatte senza risposta sono in `docs/QUESTIONS.md` (D-38…D-58, in attesa di conferma); le decisioni in ADR-0010…ADR-0014. +Le richieste dell'utente (`Modifiche.txt` del 2026-09-30), poi una revisione completa del codice con le correzioni. Versione di sviluppo 5.1.0 (`Directory.Build.props`, D-50); 559 test verdi, compilazione senza avvisi. Le scelte fatte senza risposta sono in `docs/QUESTIONS.md` (D-38…D-58, in attesa di conferma); le decisioni in ADR-0010…ADR-0014. ### Le richieste -- **Solo la password nel container** (ADR-0010): l'unica variabile è `ENCELADO_PASSWORD` («Password interfaccia» nel template Unraid; `ENCELADO_WEB_TOKEN` resta come alias deprecato). Conto, chiavi eToro dei due conti, Telegram, valuta, log, avvio automatico e strategia si impostano dalla pagina. Le chiavi e il token Telegram vivono in `/config/secrets.enc`, cifrati con la password (AES-256-GCM, PBKDF2 600 000 iterazioni); se la password cambia, i segreti si sbloccano con quella precedente o si ricomincia. Il cookie di sessione è un HMAC derivato dalla password, mai la password; `POST /logout`. Al primo avvio le variabili di un container 5.0 vengono importate una volta (`import-5.1.json`) e poi ignorate ed elencate; il caricatore non legge più l'ambiente. `run.autostart` al posto di `ENCELADO_AUTOSTART`; template, compose e Dockerfile senza PUID/PGID/TZ. +- **Solo la password nel container** (ADR-0010): l'unica variabile è `ENCELADO_PASSWORD` («Password interfaccia» nel template Unraid; `ENCELADO_WEB_TOKEN` resta come alias deprecato). Conto, chiavi eToro dei due conti, Telegram, valuta, log, avvio automatico e strategia si impostano dalla pagina. Le chiavi e il token Telegram vivono in `/config/secrets.enc`, cifrati con la password (AES-256-GCM, PBKDF2 600 000 iterazioni); se la password cambia, i segreti si sbloccano con quella precedente o si ricomincia. Il cookie di sessione è un HMAC della password e di un segreto del server (`/config/session.key`), mai la password; `POST /logout`. Al primo avvio le variabili di un container 5.0 vengono importate una volta (`import-5.1.json`) e poi ignorate ed elencate; il caricatore non legge più l'ambiente. `run.autostart` al posto di `ENCELADO_AUTOSTART`; template, compose e Dockerfile senza PUID/PGID/TZ. - **Paper eliminata**: il conto demo di eToro è il simulatore. Le modalità sono `Demo` e `Live` e scelgono anche il conto (`etoro.environment` non esiste più): chiuso il buco per cui `Demo` + ambiente `real` mandava ordini sul conto reale senza il cancello del Live. Il Live chiede `run.allowLive` e la frase `CONFERMO LIVE` scritta nell'interfaccia a ogni avvio, **non parte mai da solo** (allarme e avviso Telegram) e non ha più `ENCELADO_CONFIRM_LIVE` né `--confirm-live`. Il cambio Demo ↔ Live è rifiutato finché il conto non è piatto. - **Orologi con le bandiere** (D-49): uno per fuso delle valute trattate (Nuova Zelanda, Australia, Europa centrale/Svizzera, USA/Canada), più quello del computer solo se diverso; UTC nei tooltip. - **Log**: il livello è un'etichetta colorata e ogni messaggio sta su una riga (gli a capo diventano « ⏎ »); le parole del ledger sono in italiano (`labels.js`), il codice nel tooltip. @@ -31,20 +31,35 @@ Una revisione del codice della 5.1 ha trovato 51 problemi; quelli confermati son - **Ciclo di vita del motore**: un solo lucchetto per avvio, arresto, riavvii automatici e ciclo di apprendimento a motore fermo; FERMA durante un avvio aspetta il motore e lo ferma (prima restava un motore che operava irraggiungibile); un riavvio automatico non annulla più un FERMA arrivato prima; AVVIA subito dopo FERMA aspetta che il motore precedente lasci la cartella dati. Un kill-switch, una chiusura o la chiusura dei residui in corso non vengono mai interrotti da FERMA o da un salvataggio (409); solo `docker stop` li interrompe dopo 30 s, registrando il residuo. Ogni comando riceve una risposta («comando interrotto: il motore si è fermato», 504 con un messaggio per un'attesa scaduta, mai 500). La chiusura all'arresto (`closeOnShutdown`) è un comando sul thread di decisione, che prima blocca le entrate. «Esegui ciclo» risponde 409 finché il ciclo di decisione non è partito. Lo stream non tiene più un iscritto il cui primo tick fallisce. L'heartbeat pubblica il suo intervallo e `/api/health` usa 3 × intervallo + 15 s. - **Conti**: lo stato del motore è **per conto** (`baskets_state.demo.json`, `baskets_state.live.json`, D-53): passare da un conto all'altro non sovrascrive più chiusure in attesa del P&L, equity stop, kill-switch, residuo, pausa e picco dell'altro. Il registro degli ordini resta unico ma ogni motore tocca solo i suoi. La guardia del cambio di conto è un comando sul thread di decisione (prima leggeva la vista, piatta a metà di un ingresso), con un nuovo controllo dopo l'arresto e l'annullamento del salvataggio se il conto non è piatto. All'avvio il saldo si giudica solo quando lo storico mostra ogni chiusura: una perdita non ancora nello storico non diventa più un prelievo. - **Soldi**: la perdita giornaliera, raggiunta, **blocca fino alle 00:00 UTC anche se l'equity recupera** (D-52), nel motore e nel backtest, anche dopo un riavvio (prima il blocco cadeva appena l'equity risaliva, mentre l'interfaccia prometteva «fino a domani»); un calo del saldo che lo storico non spiega ancora sospende senza bloccare la giornata (D-54). Una posizione finisce in `baskets.csv` una volta sola (prima una chiusura vista da due percorsi poteva raddoppiare il P&L dei riepiloghi). La verifica del realizzato ha una soglia per conto (prima le righe Live restavano con i proceeds e li insegnavano ai modelli). Le gambe singole della 4.0-5.0 si abbinano alla loro nota senza indovinare. La riga di un'aggiunta richiusa non trasforma più le gambe del basket in orfane. La cache dello Storico rispetta il periodo chiesto («anno» e «tutto» non escono più calcolati su 90 giorni). La riga di `baskets.csv` e il premio del bandit nominano il preset con cui il basket è entrato. Il kill-switch fa ciò che sceglie l'operatore nel dialogo (prima chiudeva le esterne anche con la casella spenta, se l'impostazione era accesa) (D-55). -- **Segreti e web**: un file 5.0 con `Live` e ambiente `demo` resta sul conto demo dopo un salvataggio qualsiasi (prima diventava Live, scavalcando guardia, chiavi e frase). Una password errata costa un'attesa anche via Bearer e cookie, per indirizzo e fino a 30 s, e durante l'attesa non si controlla niente (D-56). Le richieste da altri siti sono rifiutate (`Content-Type: application/json` obbligatorio sotto `/api/`, controllo di `Origin` e `Sec-Fetch-Site`, `Host` locale senza password). `--sample` lavora in cartelle temporanee e non tocca più segreti, configurazione o il bot Telegram dell'operatore. La rete si apre solo nel container o con `--listen-all` (D-57). Il tick porta `statusLines` (le righe della striscia della dashboard, prima salvate e mai lette). L'importazione segue l'ordine delle chiavi della 5.0; un `secrets.enc` con un numero di iterazioni assurdo è danneggiato, non un avvio fermo per minuti; `run-docker` non stampa più la password; la pagina Apprendimento a motore fermo segue subito le modifiche di `strategy.json`. +- **Segreti e web**: un file 5.0 con `Live` e ambiente `demo` resta sul conto demo dopo un salvataggio qualsiasi (prima diventava Live, scavalcando guardia, chiavi e frase). Una password errata costa un'attesa anche via Bearer, per indirizzo e fino a 30 s, e durante l'attesa non si controlla niente (D-56). Le richieste da altri siti sono rifiutate (`Content-Type: application/json` obbligatorio sotto `/api/`, controllo di `Origin` e `Sec-Fetch-Site`, `Host` locale senza password). `--sample` lavora in cartelle temporanee e non tocca più segreti, configurazione o il bot Telegram dell'operatore. La rete si apre solo nel container o con `--listen-all` (D-57). Il tick porta `statusLines` (le righe della striscia della dashboard, prima salvate e mai lette). L'importazione segue l'ordine delle chiavi della 5.0; un `secrets.enc` con un numero di iterazioni assurdo è danneggiato, non un avvio fermo per minuti; `run-docker` non stampa più la password; la pagina Apprendimento a motore fermo segue subito le modifiche di `strategy.json`. - **Apprendimento**: i contributi mostrati spiegano sempre la `p_ML` accanto (vengono dal modello che l'ha data, salvati con l'ingresso; dopo un riavvio un basket aperto riprende la sua p); il ritiro dei modelli è tutto o niente e non si ripete; dopo la verifica del realizzato la sessione rilegge esiti e conteggio dal ledger corretto; i basket etichettati sono contati come li conta il dataset ovunque; a motore fermo la pagina segue subito le correzioni e tiene l'ultima lettura buona di un file illeggibile; un braccio del bandit mai provato non è mai «il migliore». - **Interfaccia**: impostazioni salvabili dopo due modifiche allo stesso campo; gli stati di un basket spento non sono più nascosti; filtri ricordati sempre visibili; quotazioni del Mercato che seguono il tick; «—» invece di 0 per i valori sconosciuti; fuoco su «Annulla» nelle conferme distruttive (un Invio tenuto premuto non esegue più un kill-switch); `Content-Type: application/json` su ogni POST e DELETE. - **Ledger**: la rotazione mensile delle decisioni va solo in avanti e non sovrascrive mai un file già ruotato (l'ultima barra del mese valutata dopo la mezzanotte faceva ruotare all'indietro e perdeva una riga). +### Correzioni della seconda revisione (2026-10-01) + +Una seconda verifica indipendente delle correzioni ha trovato nove punti rimasti aperti; ciascuno ha un test che lo riproduce. + +- **Stato della 5.0 al conto giusto**: il `mode` di `baskets_state.json` della 5.0 era la modalità, non il conto. Un file `Live` scritto con `etoro.environment` demo finiva nel file del conto reale, e al primo Live il saldo del demo diventava un «prelievo» di oltre 100 000 USD, con equity stop e perdita giornaliera misurati sulla cifra sbagliata; un file Paper riprendeva basket simulati sul conto demo. Ora l'importazione registra su che conto operava la 5.0 (`legacyState` in `import-5.1.json`) e il file va lì; Paper, o una modalità diversa, non vengono ripresi. +- **Comandi critici fino alla fine**: un kill-switch, una chiusura o la chiusura dei residui tengono fermi FERMA e i riavvii finché il motore li ha in mano, non finché chi li ha chiesti aspetta: chiudere la scheda, una risposta 504 dopo 120 s o Telegram spento a metà `/kill` non liberano più FERMA a metà kill-switch. +- **Chiavi salvate mentre il conto cambia**: dopo la verifica (fino a 25 s) si rilegge il conto in uso; chiavi che non sono più del conto del motore non lo riavviano, e un motore Live non viene mai riavviato senza la frase (prima restava fermo, con i basket reali sui soli stop nativi). +- **Guardia del cambio di conto**: il motore riconcilia con il conto prima di contare, così una gamba rimasta sola (richiusura rifiutata) conta come orfana invece di restare sul conto lasciato; posizioni non lette: cambio rifiutato. +- **Perdita giornaliera con lo storico in ritardo**: un calo del saldo non ancora spiegato sospende le entrate fino alla spiegazione anche se l'equity recupera (prima tornavano permesse), e la lettura che lo spiega blocca la giornata se, al minimo toccato nel frattempo, la perdita di trading superava la soglia (prima non la bloccava mai); un movimento di cassa non la blocca. Il cruscotto mostra la sospensione per tutto il tempo. +- **Apprendimento, il secondo conto**: le righe della 4.0-5.0 dell'altro conto si correggono quando quel conto gira; quell'avvio ora neutralizza di nuovo `lastNOutcomes` fino ad allora e rifà la logistica sulle etichette corrette (prima restavano l'etichetta sbagliata nel modello e una feature sbagliata, non mascherata, nelle righe della sessione intermedia). +- **Pagina Apprendimento a motore fermo**: un file mai letto bene resta «valori iniziali» anche alle letture successive (prima diventava «l'ultima lettura buona» mostrando il prior); lo stesso per `last_cycle.json`. +- **Accesso**: il cookie di sessione contiene un segreto del server (`/config/session.key`, D-56 aggiornata), quindi non è più un tentativo di password: una scheda rimasta aperta dopo un cambio di password non tiene più fuori la password giusta (prima 429 finché restava aperta), una pagina già entrata non viene fermata da chi tenta password dallo stesso indirizzo né gli azzera il conto, e l'interfaccia torna alla pagina di accesso a un 401 o 429. Serve un nuovo accesso dopo l'aggiornamento. La risposta a una password errata arriva solo a attesa davvero finita (un nuovo tentativo immediato riceveva ancora 429). +- **Test**: il preset d'ingresso è verificato dall'esecutore alla posizione e nello stato salvato (togliere una delle due righe non faceva fallire nessun test). + ### Da sapere (aggiornamento dalla 5.0) 1. Al primo avvio della 5.1 **tieni le variabili della 5.0** (anche `ENCELADO_KEY_PASSPHRASE` se le chiavi erano in `etoro.keys.enc`): vengono importate una volta. **Rinomina `ENCELADO_WEB_TOKEN` in `ENCELADO_PASSWORD` con lo stesso valore**, così i segreti restano leggibili. Poi togli dal container tutte le altre variabili (la striscia degli allarmi e Sistema ▸ Segreti le elencano). Passo per passo in `deploy/unraid/README.md`. 2. Con una password diversa i segreti risultano bloccati: Impostazioni ▸ Conto ▸ «Sblocca con la password precedente», o «Ricomincia» e reinserisci chiavi e token. -3. Il primo avvio sposta lo stato nel file del suo conto (`baskets_state.json` resta come `.migrato`), corregge il realizzato della 4.0.0-5.0.0 con righe nuove e ritira una volta i modelli addestrati sui proceeds: poi premi **Esegui ciclo** e segna `respinta` in `knowledge/proposals.csv` le proposte nate dalle etichette sbagliate. +3. Il primo avvio sposta lo stato nel file del conto su cui operava la 5.0 (`baskets_state.json` resta come `.migrato`; lo stato di Paper non viene ripreso), corregge il realizzato della 4.0.0-5.0.0 con righe nuove e ritira una volta i modelli addestrati sui proceeds: poi premi **Esegui ciclo** e segna `respinta` in `knowledge/proposals.csv` le proposte nate dalle etichette sbagliate. 4. I messaggi Telegram e i log già inviati dalla 4.0.0 alla 5.0.0 con il «netto» e il «P&L oggi» sbagliati restano come sono: il ledger è corretto, la cronologia no. 5. In Live il motore non riparte più da solo dopo un riavvio: AVVIA e `CONFERMO LIVE`, ogni volta. 6. Gli script che chiamano l'API devono mandare `Content-Type: application/json` su ogni POST e DELETE; dietro un reverse proxy il proxy deve passare l'`Host` originale (`docs/DOCKER.md`). 7. Il preset si cambia solo da Impostazioni ▸ Strategia; il comando `preset` (console, web) non esiste più. +8. Dopo l'aggiornamento serve un nuovo accesso alla pagina (il cookie contiene ora un segreto del server, `/config/session.key`; cancellarlo chiude tutte le sessioni). ## 2026-09-23 — 5.0.0 rilasciata; workflow Gitea Actions; guida Unraid diff --git a/Encelado/deploy/unraid/README.md b/Encelado/deploy/unraid/README.md index 1b2af0a..318ace2 100644 --- a/Encelado/deploy/unraid/README.md +++ b/Encelado/deploy/unraid/README.md @@ -89,11 +89,15 @@ legge **una volta sola**, al primo avvio, e poi le ignora. Quindi: `etoro.keys.enc` diventa `etoro.keys.enc.migrato`; - sposta lo stato del motore nel file del suo conto (`baskets_state.json` → `baskets_state.demo.json` o `.live.json`; l'originale resta come `.migrato`) e riprende i - basket aperti; + basket aperti. Il conto è quello su cui lavorava la 5.0 (con `ENCELADO_EXECUTION_MODE=Live` + e `ETORO_ENVIRONMENT=demo` era il conto demo): per questo al primo avvio le variabili vanno + lasciate come sono. Lo stato della modalità Paper non viene ripreso (il log dice «non + ripreso: …»); - verifica sullo storico eToro il P&L delle righe scritte dalla 4.0.0-5.0.0 (che erano i proceeds delle chiusure, non il profitto) e scrive righe di correzione; se ne ha corrette, mette da parte una volta i modelli addestrati su quei numeri. -4. Apri la pagina con la **stessa password**. Controlla **Sistema ▸ Segreti** (chiavi del conto +4. Apri la pagina con la **stessa password** (serve un nuovo accesso: il cookie della 5.1 contiene + anche un segreto del server, `/config/session.key`, creato ora). Controlla **Sistema ▸ Segreti** (chiavi del conto demo, ed eventualmente reale, presenti; la nota dell'importazione) e la striscia sotto la barra in alto: «Variabili d'ambiente ignorate: …» elenca quelle da togliere. 5. *Edit* di nuovo e **togli tutte le variabili tranne `ENCELADO_PASSWORD`**: `ETORO_API_KEY`, diff --git a/Encelado/docs/API.md b/Encelado/docs/API.md index 183b487..01b5799 100644 --- a/Encelado/docs/API.md +++ b/Encelado/docs/API.md @@ -10,7 +10,7 @@ Aggiornato: 2026-10-01. È il contratto fra il server (`src/Encelado.Server/Web` - Numeri non finiti (NaN, ∞) → `null`. Un valore sconosciuto è `null`, mai `0`. - Testi per l'operatore (motivazioni, intenti, messaggi) in italiano. - Le risposte dei comandi e delle scritture hanno sempre `{ "ok": bool, "message": string }` più i campi propri. -- Autenticazione: se il container ha `ENCELADO_PASSWORD` (alias deprecato `ENCELADO_WEB_TOKEN`) ogni rotta chiede il cookie `encelado_session` o `Authorization: Bearer `; senza sessione le rotte `/api/*` rispondono **401**, le pagine rimandano a `/login`. Libere: `/login`, `/api/health`, `/css/*`, `/img/*`, `/icon.svg`, `/manifest.webmanifest`. Una password errata — dal form, dall'header Bearer o dal cookie (derivato dalla password, quindi anch'esso un tentativo) — costa al suo indirizzo un'attesa che raddoppia fino a 30 s (vedi [Accesso](#accesso)). +- Autenticazione: se il container ha `ENCELADO_PASSWORD` (alias deprecato `ENCELADO_WEB_TOKEN`) ogni rotta chiede il cookie `encelado_session` o `Authorization: Bearer `; senza sessione le rotte `/api/*` rispondono **401**, le pagine rimandano a `/login`. Libere: `/login`, `/api/health`, `/css/*`, `/img/*`, `/icon.svg`, `/manifest.webmanifest`. Una password errata — dal form o dall'header Bearer — costa al suo indirizzo un'attesa che raddoppia fino a 30 s (vedi [Accesso](#accesso)); il cookie non è una password: valido entra anche durante l'attesa, sbagliato riceve 401 subito. - Rete: il server ascolta su tutte le interfacce solo con una password **e** nel container (o con l'argomento `--listen-all`); fuori dal container (F5, `run-dev`) resta su localhost anche con la password, che lì serve ai segreti della sandbox. Senza password ascolta solo su localhost e non chiede niente. - Richieste da altrove: vedi [Richieste che cambiano qualcosa](#richieste-che-cambiano-qualcosa) (`Content-Type: application/json`, `Origin`, `Sec-Fetch-Site`, Host senza password). - `--sample`: ogni rotta risponde con dati d'esempio realistici e coerenti fra loro (nessuna chiave, nessun mercato), per lavorare sulle pagine e fotografarle. Il server campione lavora in cartelle temporanee (cancellate all'uscita): non legge né scrive la configurazione, i segreti o i dati dell'operatore e non apre il bot Telegram. Le impostazioni sono quelle di fabbrica e ogni scrittura (comandi, impostazioni, segreti) risponde **400** «modalità dimostrativa (--sample)». @@ -24,11 +24,11 @@ L'interfaccia (docs/UI_GUIDELINES.md): `index.html` carica `/css/tokens.css`, `/ ## Accesso - `GET /login` — la pagina. -- `POST /login` — form `password` (accettato anche `token`, il nome della 5.0). Corretta: cookie `encelado_session` (HttpOnly, SameSite=Strict, 30 giorni) e **302** su `/`. Il cookie è un HMAC derivato dalla password, mai la password: cambiarla invalida le sessioni. Errata: **401** con la pagina di login e il messaggio (` +/// Whose a state file of 5.0 is (5.1 review): 5.0 kept two settings, the execution mode — the +/// mode its state file names — and etoro.environment, the account it traded on. A +/// file saying Live was the demo account's when the environment said demo, one saying +/// Demo the real account's when it said real, and Paper was the simulator, on no +/// account. The one-time import records what the 5.0 configuration said (import-5.1.json); +/// is the mode such a file names (Paper, Demo, Live), +/// the account it traded on, null for Paper. +/// +public sealed record LegacyStateOwner(string Mode, ExecutionMode? Account) +{ + /// + /// What a 5.0 configuration (its mode and environment, the variables winning over the file as in + /// 5.0) says about its state file; null when it names no environment and is not Paper: a file of + /// 5.1, which says nothing about 5.0. + /// + public static LegacyStateOwner? Of(string? mode, string? environment) + { + bool paper = IsPaper(mode); + if (!paper && string.IsNullOrWhiteSpace(environment)) + { + return null; + } + + if (paper) + { + return new LegacyStateOwner("Paper", null); + } + + ExecutionModeExtensions.TryParse(mode ?? "Demo", out ExecutionMode parsed); + ExecutionMode account = environment!.Trim().Equals("real", StringComparison.OrdinalIgnoreCase) ? ExecutionMode.Live : ExecutionMode.Demo; + return new LegacyStateOwner(parsed.IsLive() ? "Live" : "Demo", account); + } + + /// Whether a mode name is 5.0's simulator (read as Demo since 5.1). + public static bool IsPaper(string? mode) => (mode ?? string.Empty).Trim().Equals("paper", StringComparison.OrdinalIgnoreCase); +} + +/// What the move of the single old file did, for the log: false when it went aside unread. +public sealed record LegacyMigration(string Message, bool Taken); + /// /// The engine's state on disk, one file per account (5.1 review, decision D-53): /// data/state/baskets_state.demo.json and data/state/baskets_state.live.json. @@ -12,10 +55,12 @@ namespace Encelado.Engine.Baskets; /// back finds them where they were. /// /// The single baskets_state.json of 5.0 and of the first 5.1 builds goes, once, to the -/// account its mode names — whichever account the engine that finds it trades — and -/// stays beside it renamed .migrato: never deleted, never saved over. Only an engine -/// holding the data folder's instance lock migrates; a reader (the account-switch guard) -/// reads the old file for its own account until then. +/// account it belongs to () — whichever account the engine that finds +/// it trades — and stays beside it renamed .migrato: never deleted, never saved over. A +/// file whose account cannot be told (a Paper simulator's, one written under another 5.0 +/// configuration) goes aside unread, as 5.0 dropped the state of another mode. Only an engine +/// holding the data folder's instance lock migrates; a reader (the account-switch guard) reads +/// the old file for the account it belongs to until then. /// /// public static class AccountStateFiles @@ -47,12 +92,66 @@ public static class AccountStateFiles DateTime.TryParse(s.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t) ? t : DateTime.MinValue; /// - /// The file a reader takes for : the account's own, or — before - /// an engine migrated it — the single old file when it is that account's (or names none). - /// Null when there is neither. Reads only: the guard of the settings page must not touch - /// the engine's files. + /// The account the single old file belongs to; null when it must go aside unread ( says why). + /// + /// A file of 5.1 (it has pendingSettlements, which 5.0 never wrote): its mode is + /// the account, as mode and account are one since decision C6. + /// A file of 5.0 or 4.0: its mode is the execution mode, not the account (5.1 review). + /// Paper goes aside: its baskets were simulated, on no account. With the import's record of the + /// 5.0 configuration (), the account that configuration traded on, when + /// the file names the mode it ran; another mode means the file was written under another + /// configuration, and goes aside. Without a record, only 's account + /// takes it, when the file names that mode — what 5.0 itself resumed. + /// A file naming no mode: 's, as 5.0 read it. + /// /// - public static string? ReadablePathFor(string dataPath, ExecutionMode account) + public static ExecutionMode? LegacyTarget(JsonElement root, ExecutionMode running, LegacyStateOwner? owner, out string why) + { + why = string.Empty; + string? raw = root.ValueKind == JsonValueKind.Object && root.TryGetProperty("mode", out JsonElement m) && m.ValueKind == JsonValueKind.String ? m.GetString() : null; + if (LegacyStateOwner.IsPaper(raw)) + { + why = "è del simulatore Paper della 5.0: i suoi basket non sono su nessun conto eToro"; + return null; + } + + if (string.IsNullOrWhiteSpace(raw) || !ExecutionModeExtensions.TryParse(raw, out ExecutionMode named)) + { + return running; + } + + if (root.TryGetProperty("pendingSettlements", out _)) + { + return named; + } + + if (owner is not null) + { + if (owner.Account is { } account && owner.Mode.Equals(named.IsLive() ? "Live" : "Demo", StringComparison.Ordinal)) + { + return account; + } + + why = $"è stato scritto in modalità {raw}, ma la configurazione della 5.0 era in {owner.Mode}: di quale conto fosse non si può dire"; + return null; + } + + if (named.IsLive() == running.IsLive()) + { + return running; + } + + why = $"è della 5.0 in modalità {raw}, che non dice su quale conto operava (lo diceva etoro.environment), e l'importazione non l'ha registrato"; + return null; + } + + /// + /// The file a reader takes for : the account's own, or — before + /// an engine migrated it — the single old file when it belongs to that account + /// (, as an engine of that account would decide). Null when there is + /// neither. Reads only: the guard of the settings page must not touch the engine's files. + /// + public static string? ReadablePathFor(string dataPath, ExecutionMode account, LegacyStateOwner? owner = null) { string own = PathFor(dataPath, account); if (File.Exists(own)) @@ -69,7 +168,7 @@ public static class AccountStateFiles try { using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(legacy)); - return ModeOf(doc.RootElement) is not { } mode || mode.IsLive() == account.IsLive() ? legacy : null; + return LegacyTarget(doc.RootElement, account, owner, out _) is { } target && target.IsLive() == account.IsLive() ? legacy : null; } catch (JsonException) { @@ -79,14 +178,14 @@ public static class AccountStateFiles } /// - /// Moves the single old file to the account its mode names ('s - /// when it names none, as 5.0 read it), then renames it .migrato. When that account - /// already has its own file, the more recent of the two wins (a return to an older version - /// and back) and the other stays beside it. Returns what happened for the log, or null when - /// there was nothing to do. Throws on a file-system error: the start must not go on and - /// save an empty state over what it could not move. + /// Moves the single old file to the account it belongs to (), then + /// renames it .migrato; a file whose account cannot be told is only renamed, never read + /// into a state. When the account already has its own file, the more recent of the two wins (a + /// return to an older version and back) and the other stays beside it. Returns what happened + /// for the log, or null when there was nothing to do. Throws on a file-system error: the start + /// must not go on and save an empty state over what it could not move. /// - public static string? MigrateLegacy(string dataPath, ExecutionMode running) + public static LegacyMigration? MigrateLegacy(string dataPath, ExecutionMode running, LegacyStateOwner? owner = null) { string legacy = LegacyPath(dataPath); if (!File.Exists(legacy)) @@ -95,31 +194,47 @@ public static class AccountStateFiles } byte[] bytes = File.ReadAllBytes(legacy); - ExecutionMode account; + ExecutionMode? belongs; DateTime saved; + string why; + string? named; try { using JsonDocument doc = JsonDocument.Parse(bytes); - account = ModeOf(doc.RootElement) ?? running; + if (doc.RootElement.ValueKind != JsonValueKind.Object) + { + throw new JsonException("non è un oggetto JSON"); + } + + belongs = LegacyTarget(doc.RootElement, running, owner, out why); saved = SavedUtcOf(doc.RootElement); + named = doc.RootElement.TryGetProperty("mode", out JsonElement m) && m.ValueKind == JsonValueKind.String ? m.GetString() : null; } catch (JsonException ex) { string aside = MoveAside(legacy, "illeggibile"); - return $"{LegacyName} non leggibile ({ex.Message}): spostato in {Path.GetFileName(aside)}, il motore riparte dalla riconciliazione con il conto"; + return new LegacyMigration($"{LegacyName} non leggibile ({ex.Message}): spostato in {Path.GetFileName(aside)}, il motore riparte dalla riconciliazione con il conto", false); } + if (belongs is not { } account) + { + string kept = MoveAside(legacy, "migrato"); + return new LegacyMigration($"stato della versione precedente ({LegacyName}) non ripreso: {why}. Resta com'è come {Path.GetFileName(kept)}; le posizioni del conto si riconciliano dal conto stesso", false); + } + + // The account's file names its account (a 5.0 file named its mode: "Live" may be the demo account's). string target = PathFor(dataPath, account); + byte[] content = string.Equals(named, account.ToString(), StringComparison.Ordinal) ? bytes : WithMode(bytes, account); string outcome; if (!File.Exists(target)) { - AtomicFile.Write(target, bytes); + AtomicFile.Write(target, content); outcome = $"diventa {Path.GetFileName(target)}"; } else if (saved > SavedUtcOfFile(target)) { string previous = MoveAside(target, "precedente"); - AtomicFile.Write(target, bytes); + AtomicFile.Write(target, content); outcome = $"è più recente di {Path.GetFileName(target)} e ne prende il posto (il precedente resta come {Path.GetFileName(previous)})"; } else @@ -128,7 +243,15 @@ public static class AccountStateFiles } string migrated = MoveAside(legacy, "migrato"); - return $"stato del conto {account.Account()} della versione precedente ({LegacyName}): {outcome}; l'originale resta come {Path.GetFileName(migrated)}"; + return new LegacyMigration($"stato del conto {account.Account()} della versione precedente ({LegacyName}): {outcome}; l'originale resta come {Path.GetFileName(migrated)}", true); + } + + /// The saved state with mode set to the account it now belongs to; everything else as it was. + private static byte[] WithMode(byte[] bytes, ExecutionMode account) + { + JsonObject root = JsonNode.Parse(bytes) as JsonObject ?? throw new JsonException("lo stato salvato non è un oggetto JSON"); + root["mode"] = account.ToString(); + return Encoding.UTF8.GetBytes(root.ToJsonString(new JsonSerializerOptions { WriteIndented = true })); } /// Renames a file beside itself with a tag (and the time, when the name is taken); returns the new path. diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Commands.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Commands.cs index bfd9821..df2d5ee 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Commands.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Commands.cs @@ -23,12 +23,44 @@ public sealed partial class BasketEngine /// What blocks entries and adds once the stop began (). private const string StopReason = "arresto del motore in corso"; - /// Guards : a command is queued before the queue closes, or answered at once after. + /// Guards and : a command is queued before the queue closes, or answered at once after. private readonly Lock _commandGate = new(); /// Set when the run ended: nobody takes commands any more. private bool _commandsClosed; + /// + /// The critical commands queued or running on the decision thread (), from the + /// queue until the decision thread is done with them or the run ends without them — never only while their + /// caller waits (5.1 second review). + /// + private readonly List _criticalInHand = []; + + public string? CriticalCommand + { + get + { + lock (_commandGate) + { + return _criticalInHand.Count > 0 ? _criticalInHand[0].Describe() : null; + } + } + } + + /// The decision thread is done with a command (executed, failed, cut by the stop, or never taken). + private void DoneWith(EngineCommand command) + { + if (!command.IsCritical) + { + return; + } + + lock (_commandGate) + { + _criticalInHand.Remove(command); + } + } + /// Set by the loop when it begins (). private bool _loopStarted; @@ -55,6 +87,12 @@ public sealed partial class BasketEngine { if (!_commandsClosed) { + // Counted from here, not while the caller waits: the decision thread runs it whatever the caller does. + if (command.IsCritical) + { + _criticalInHand.Add(command); + } + _commands.Enqueue((command, tcs)); return tcs.Task.WaitAsync(CommandWait, ct); } @@ -65,7 +103,8 @@ public sealed partial class BasketEngine return Task.FromResult(Interrupted); } - private async Task DrainCommandsAsync(CancellationToken ct) + /// Runs every queued command, as the loop does at the top of a tick (internal: the tests drain the queue themselves). + internal async Task DrainCommandsAsync(CancellationToken ct) { while (_commands.TryDequeue(out (EngineCommand Command, TaskCompletionSource Done) item)) { @@ -88,6 +127,7 @@ public sealed partial class BasketEngine } finally { + DoneWith(item.Command); NoteCommand(item.Command, result); item.Done.TrySetResult(result); } @@ -110,6 +150,7 @@ public sealed partial class BasketEngine { CommandResult result = Interrupted; Log.Warn($"comando {item.Command.Kind} non eseguito: il motore si è fermato prima di prenderlo"); + DoneWith(item.Command); NoteCommand(item.Command, result); item.Done.TrySetResult(result); } @@ -245,7 +286,7 @@ public sealed partial class BasketEngine return await PrepareStopAsync(c, ct).ConfigureAwait(false); case EngineCommandKind.PrepareAccountSwitch: - return PrepareAccountSwitch(c); + return await PrepareAccountSwitchAsync(c, ct).ConfigureAwait(false); case EngineCommandKind.CancelAccountSwitch: return CancelAccountSwitch(c); @@ -278,14 +319,20 @@ public sealed partial class BasketEngine /// /// The guard of a change of account or of the basket pairs: first no new entry and no add, - /// then the count. With something still in hand the block is lifted and the switch refused; - /// with nothing, the entries stay blocked until the restart on the other account. + /// then a reconciliation with the account, then the count. The reconciliation comes first (5.1 + /// second review): a leg of ours that no slot holds — leg A left on the account when its unwind + /// close was refused, a fill nobody waited for — is in the last reconciliation's picture only up + /// to twenty seconds later, and would be left behind on the old account; read now, it is an + /// orphan and counts. Positions that cannot be read leave the account unknown: refused. With + /// something still in hand the block is lifted and the switch refused; with nothing, the + /// entries stay blocked until the restart on the other account. /// - private CommandResult PrepareAccountSwitch(EngineCommand c) + private async Task PrepareAccountSwitchAsync(EngineCommand c, CancellationToken ct) { string what = c.Argument.Length > 0 ? c.Argument : "cambio di conto"; _switchBlock = $"{what} in corso: nessuna nuova entrata fino al riavvio"; - AccountActivity activity = CurrentActivity(); + bool read = !_stateLoaded || await ReconcileStepAsync(DateTime.UtcNow, ct).ConfigureAwait(false); + AccountActivity activity = CurrentActivity() with { AccountUnread = !read }; if (activity.Busy) { _switchBlock = null; diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Realized.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Realized.cs index 5c2384d..29f4e27 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Realized.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Realized.cs @@ -49,6 +49,9 @@ public sealed partial class BasketEngine return trades; } + /// The next reading asks the venue again (internal: the tests change the history between two readings closer than three seconds). + internal void ForgetHistoryReading() => _historyCache = null; + /// /// Settles the closes the history shows (or that waited past 30 minutes), then /// recomputes today's realised result. Runs when due (see ); @@ -106,16 +109,21 @@ public sealed partial class BasketEngine /// venue's labels. When rows of those versions were wrong, once: the feature is declared /// unreliable up to now — the rows before were computed from the wrong labels, those after /// are right whatever happens to the retire — the notes' proceeds range is recorded, and the - /// models that learnt from the wrong labels are retired and rebuilt. A failure is retried at - /// the next start. Internal: the tests drive it over their own venue. + /// models that learnt from the wrong labels are retired and rebuilt. The other account's rows + /// are corrected only when it runs (5.1 second review): a later start that corrects rows of + /// those versions declares the feature unreliable again up to now — the sessions in between + /// computed it with their wrong labels — and replays the logistic on the corrected labels; + /// the bandit, restarted from its prior by the retire, never learnt them. A failure is + /// retried at the next start. Internal: the tests drive it over their own venue. /// internal async Task BackfillRealizedAsync(CancellationToken ct) { + BackfillReport report; try { RealizedBackfill backfill = new(_ledger, (from, token) => _broker.GetClosedTradesAsync(from, token), _runId, ModeLabel, symbol => _series.TryGetValue(symbol, out SymbolSeries? s) ? s.Instrument.Id : 0, static m => Log.Info(m)); - BackfillReport report = await backfill.RunAsync(DateTime.UtcNow, ct).ConfigureAwait(false); + report = await backfill.RunAsync(DateTime.UtcNow, ct).ConfigureAwait(false); if (report.Corrected + report.Unverifiable > 0) { Log.Warn($"verifica del realizzato: {report.Describe()} (righe di baskets.csv corrette con righe «correzione» in decisions.jsonl; il file non viene toccato)"); @@ -130,14 +138,28 @@ public sealed partial class BasketEngine try { Learner.Reseed(); - if (Learner.LabelsFixed || !RealizedBackfill.LegacyRowsWereCorrected(_ledger)) + DateTime now = DateTime.UtcNow; + string feature = LearningFeatures.Names[LearningFeatures.LastOutcomesIndex]; + if (Learner.LabelsFixed) + { + if (report.CorrectedLegacy > 0) + { + // The mark goes first: the replay below must already see the feature masked. + _ledger.FeatureUnreliable(_runId, feature, LearningFeatures.LastOutcomesIndex, now, string.Create(CultureInfo.InvariantCulture, + $"lastNOutcomes calcolata fino a questo momento anche con {report.CorrectedLegacy} etichette sbagliate del conto {(_mode.IsLive() ? "reale" : "demo")} (P&L = proceeds della chiusura), corrette solo ora: nel dataset vale 0,5, il valore neutro")); + Learner.ReplayLogistic(now, string.Create(CultureInfo.InvariantCulture, $"{report.CorrectedLegacy} etichette 4.0.0-5.0.0 del conto {(_mode.IsLive() ? "reale" : "demo")} corrette dallo storico eToro: logistica rifatta sulle etichette corrette")); + _versions.Bump(Section.Learning); + } + + return; + } + + if (!RealizedBackfill.LegacyRowsWereCorrected(_ledger)) { return; } // The mark goes first: the replay below must already see the feature masked. - DateTime now = DateTime.UtcNow; - string feature = LearningFeatures.Names[LearningFeatures.LastOutcomesIndex]; if (_ledger.ReadFeatureMaskUntil(feature) == DateTime.MinValue) { _ledger.FeatureUnreliable(_runId, feature, LearningFeatures.LastOutcomesIndex, now, diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Reconcile.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Reconcile.cs index 081d05b..571819a 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Reconcile.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Reconcile.cs @@ -68,7 +68,8 @@ public sealed partial class BasketEngine } // Every reading is judged against the daily loss (D-52): a dip between two bar closes blocks the day too. - UpdateDailyLoss(); + // A reading with a verdict on the cash also judges the low of a fall the history had not explained yet. + UpdateDailyLoss(verdict: double.IsFinite(closedNetSinceLast)); if (movement is not null) { @@ -216,13 +217,29 @@ public sealed partial class BasketEngine return s.NetUsd + _pendingClosedNet; } + /// + /// The reconciliation step of the loop, also asked by the guard of a change of account (5.1 + /// second review): the reconciliation, the equity stop on what it read, the state saved and + /// the picture published. False when the account's positions could not be read. + /// + private async Task ReconcileStepAsync(DateTime now, CancellationToken ct) + { + _lastReconcileUtc = now; + bool read = await ReconcileAsync(ct).ConfigureAwait(false); + await CheckEquityStopAsync(ct).ConfigureAwait(false); + SaveState(); + PublishView(); + return read; + } + /// /// Positions on the venue against the local state: a leg that vanished closes its /// sibling; every position is classified; orphans of ours are adopted and closed; - /// strangers are reported once and left alone; the two pictures are compared. + /// strangers are reported once and left alone; the two pictures are compared. False + /// when the positions could not be read (nothing was compared nor classified). /// Internal: the tests drive it over their own venue. /// - internal async Task ReconcileAsync(CancellationToken ct) + internal async Task ReconcileAsync(CancellationToken ct) { IReadOnlyList positions; try @@ -234,7 +251,7 @@ public sealed partial class BasketEngine Log.Warn($"riconciliazione non riuscita: {ex.Message}"); _positionsView = _positionsView with { Problem = $"riconciliazione non riuscita: {ex.Message}" }; _versions.Bump(Section.Positions); - return; + return false; } HashSet onVenue = [.. positions.Select(static p => p.PositionId)]; @@ -418,6 +435,8 @@ public sealed partial class BasketEngine Log.Warn($"posizioni non riconciliate da {(DateTime.UtcNow - _unreconciledSince.Value).TotalSeconds:0} s: {problem}"); } } + + return true; } /// diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs index df0e2ad..8cdcca7 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs @@ -1,6 +1,7 @@ using System.Globalization; using System.Text.Json; using Encelado.Engine; +using Encelado.Engine.Configuration; using Encelado.Engine.Logging; using Encelado.Core.Baskets; using Encelado.Core.Baskets.History; @@ -165,8 +166,9 @@ public sealed partial class BasketEngine /// /// Reads this account's state (internal: the tests load it without a venue). The single - /// file of the previous versions first goes to the account it names — this one or the - /// other — so it is never read by the wrong account nor saved over (5.1 review, D-53). + /// file of the previous versions first goes to the account it belongs to — this one or the + /// other, by the import's record of the 5.0 configuration — or aside when that cannot be + /// told, so it is never read by the wrong account nor saved over (5.1 review, D-53). /// internal void LoadState() { @@ -179,9 +181,16 @@ public sealed partial class BasketEngine // stops the start before anything could be saved over what was not moved. try { - if (AccountStateFiles.MigrateLegacy(_dataDir, _mode) is { } migrated) + if (AccountStateFiles.MigrateLegacy(_dataDir, _mode, EnvironmentImport.ReadLegacyStateOwner(_config.Run.BaseDirectory)) is { } migrated) { - Log.Info(migrated); + if (migrated.Taken) + { + Log.Info(migrated.Message); + } + else + { + Log.Warn(migrated.Message); + } } } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.View.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.View.cs index 1defa6f..756a02a 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.View.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.View.cs @@ -108,7 +108,7 @@ public sealed partial class BasketEngine TodayEquityChange = TodayEquityChange, TodayClosed = _today.Closed, DailyLossUsedPct = DailyLoss.UsedFraction(_dayStartEquity, netEquity, _strategy.DailyLossPct), - DailyLossHit = DailyLoss.IsHit(_dayStartEquity, netEquity, _strategy.DailyLossPct), + DailyLossHit = DailyLoss.IsHit(_dayStartEquity, netEquity, _strategy.DailyLossPct) || WaitingDailyLossHit, DailyLossLatched = _dailyLoss.IsLatched(_sessionDate), PendingSettlements = _settlements.Queue.Count, }; diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs index f5db97a..4e85a7c 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs @@ -758,11 +758,7 @@ public sealed partial class BasketEngine : IEngine if (now - _lastReconcileUtc >= reconcile) { - _lastReconcileUtc = now; - await ReconcileAsync(ct).ConfigureAwait(false); - await CheckEquityStopAsync(ct).ConfigureAwait(false); - SaveState(); - PublishView(); + await ReconcileStepAsync(now, ct).ConfigureAwait(false); } // One reading of the venue's history settles the closes, recomputes today's @@ -1257,30 +1253,84 @@ public sealed partial class BasketEngine : IEngine internal Task ContextAsync(string basket, CancellationToken ct) => BuildContextAsync(_slots.First(s => s.Name.Equals(basket, StringComparison.OrdinalIgnoreCase)), DateTime.UtcNow, isBarClose: true, ct); + /// + /// The lowest account equity seen while a fall of the balance waits for the venue's history to explain + /// it (5.1 second review); NaN while no fall waits. is the cash + /// flow when the wait began: no verdict on cash is taken until the history explains the fall. + /// + private double _lowestEquityUnexplained = double.NaN; + + private double _cashFlowBeforeUnexplained; + + /// + /// A fall the history has not explained yet took the net equity past the daily loss at its low: new entries + /// stay suspended until it is explained, even if the equity recovered meanwhile (the view says so too). + /// + private bool WaitingDailyLossHit => + double.IsFinite(_lowestEquityUnexplained) && DailyLoss.IsHit(_dayStartEquity, _lowestEquityUnexplained - _cashFlowBeforeUnexplained, _strategy.DailyLossPct); + /// /// The daily-loss rule on the latest net equity (D-52): hit once, the block holds for the rest /// of the UTC day even if the equity recovers. Taken at every account reading and every /// decision, so a dip seen between two bar closes blocks the day too. A fall of the balance the /// venue has not explained yet (its history lags a close by seconds to minutes) may be a - /// withdrawal: it blocks at once, but the day is latched only on the loss that remains even if - /// all of it were cash taken out — the reading that explains it latches the rest. The day's - /// first hit is announced once and saved at once (a restart keeps the block). Decision thread only. + /// withdrawal (D-54): new entries are suspended until the history explains it — measured on the + /// lowest equity seen meanwhile, so a recovery does not lift the suspension — but the day is + /// latched only on the loss that remains even if all of it were cash taken out. The reading that + /// explains it (: the cash movements are judged on it) then judges the + /// day on that low (5.1 second review): a trading loss latches the day even if the equity + /// recovered meanwhile; cash that moved never does — a withdrawal was gone at the low, a deposit + /// may have come after it. The day's first hit is announced once and saved at once (a restart + /// keeps the block). Decision thread only. /// - private bool UpdateDailyLoss() + private bool UpdateDailyLoss(bool verdict = false) { bool latchedBefore = _dailyLoss.IsLatched(_sessionDate); + double pct = _strategy.DailyLossPct; double netEquity = NetEquityNow; - double unexplained = _account.TimeUtc != DateTime.MinValue && double.IsFinite(_equity.LastBalance) ? Math.Max(0, _equity.LastBalance - _account.Balance) : 0; - bool hitNow = DailyLoss.IsHit(_dayStartEquity, netEquity, _strategy.DailyLossPct); - bool blocked = _dailyLoss.Evaluate(_sessionDate, _dayStartEquity, netEquity + unexplained, _strategy.DailyLossPct) || hitNow; double dailyPnl = _dayStartEquity > 0 && double.IsFinite(netEquity) ? netEquity - _dayStartEquity : double.NaN; + double reported = dailyPnl; + if (verdict && double.IsFinite(_lowestEquityUnexplained)) + { + // Explained at this very reading: what the history called cash is in the cash flow now. + double booked = _equity.CumulativeCashFlow - _cashFlowBeforeUnexplained; + double lowNet = _lowestEquityUnexplained - (_cashFlowBeforeUnexplained + Math.Min(0, booked)); + bool suspended = DailyLoss.IsHit(_dayStartEquity, _lowestEquityUnexplained - _cashFlowBeforeUnexplained, pct); + _lowestEquityUnexplained = double.NaN; + if (_dailyLoss.Evaluate(_sessionDate, _dayStartEquity, lowNet, pct)) + { + reported = lowNet - _dayStartEquity; + } + else if (suspended) + { + Log.Info(string.Create(CultureInfo.InvariantCulture, $"lo storico eToro spiega il calo del saldo: {(booked < 0 ? $"un prelievo di {-booked:F2} USD" : "nessuna perdita oltre la soglia")}; la giornata non si blocca e le nuove entrate sono di nuovo permesse")); + } + } + + double unexplained = _account.TimeUtc != DateTime.MinValue && double.IsFinite(_equity.LastBalance) ? Math.Max(0, _equity.LastBalance - _account.Balance) : 0; + if (unexplained > 0) + { + if (!double.IsFinite(_lowestEquityUnexplained)) + { + _cashFlowBeforeUnexplained = _equity.CumulativeCashFlow; + _lowestEquityUnexplained = _account.Equity; + } + else + { + _lowestEquityUnexplained = Math.Min(_lowestEquityUnexplained, _account.Equity); + } + } + + bool hitNow = DailyLoss.IsHit(_dayStartEquity, netEquity, pct); + bool waitingHit = WaitingDailyLossHit; + bool blocked = _dailyLoss.Evaluate(_sessionDate, _dayStartEquity, netEquity + unexplained, pct) || hitNow || waitingHit; if (_dailyLoss.IsLatched(_sessionDate)) { if (_dailyLossNotified != _sessionDate) { _dailyLossNotified = _sessionDate; - Log.Warn(string.Create(CultureInfo.InvariantCulture, $"perdita giornaliera raggiunta: equity netta {dailyPnl:+0.00;-0.00} USD da mezzanotte su {_dayStartEquity:F2} di partenza ({_strategy.DailyLossPct:0.#} %): niente nuove entrate né aggiunte fino alle 00:00 UTC, anche se l'equity recupera; le uscite restano attive")); - _notifier.Notify(NotificationKind.Alert, "Perdita giornaliera raggiunta", string.Create(CultureInfo.InvariantCulture, $"equity netta {dailyPnl:+0.00;-0.00} USD da mezzanotte su {_dayStartEquity:N2} ({_strategy.DailyLossPct:0.#} %): niente nuove entrate fino alle 00:00 UTC, anche se l'equity recupera")); + Log.Warn(string.Create(CultureInfo.InvariantCulture, $"perdita giornaliera raggiunta: equity netta {reported:+0.00;-0.00} USD da mezzanotte su {_dayStartEquity:F2} di partenza ({pct:0.#} %): niente nuove entrate né aggiunte fino alle 00:00 UTC, anche se l'equity recupera; le uscite restano attive")); + _notifier.Notify(NotificationKind.Alert, "Perdita giornaliera raggiunta", string.Create(CultureInfo.InvariantCulture, $"equity netta {reported:+0.00;-0.00} USD da mezzanotte su {_dayStartEquity:N2} ({pct:0.#} %): niente nuove entrate fino alle 00:00 UTC, anche se l'equity recupera")); } if (!latchedBefore) @@ -1288,10 +1338,10 @@ public sealed partial class BasketEngine : IEngine SaveState(); } } - else if (hitNow && _dailyLossUnexplainedNoted != _sessionDate) + else if ((hitNow || waitingHit) && _dailyLossUnexplainedNoted != _sessionDate) { _dailyLossUnexplainedNoted = _sessionDate; - Log.Warn(string.Create(CultureInfo.InvariantCulture, $"equity netta {dailyPnl:+0.00;-0.00} USD da mezzanotte, oltre la perdita giornaliera ({_strategy.DailyLossPct:0.#} %), con un calo del saldo di {unexplained:F2} USD che lo storico eToro non spiega ancora (forse un prelievo): nuove entrate sospese finché non si chiarisce; se è una perdita, blocco fino alle 00:00 UTC")); + Log.Warn(string.Create(CultureInfo.InvariantCulture, $"equity netta {dailyPnl:+0.00;-0.00} USD da mezzanotte, oltre la perdita giornaliera ({pct:0.#} %) almeno per un momento, con un calo del saldo di {unexplained:F2} USD che lo storico eToro non spiega ancora (forse un prelievo): nuove entrate sospese finché non si chiarisce, anche se l'equity recupera; se è una perdita, blocco fino alle 00:00 UTC")); } return blocked; @@ -1719,8 +1769,10 @@ public sealed partial class BasketEngine : IEngine _sessionDate = today; // The day starts at the first account reading of the new day (asked for now), and - // its realised result from the first reading of its history: unknown until then. + // its realised result from the first reading of its history: unknown until then. A fall + // still waiting for the history belonged to the day before, whose block ended now. _dayStartEquity = double.NaN; + _lowestEquityUnexplained = double.NaN; _today.Roll(now); _nextHistoryUtc = DateTime.MinValue; _lastReconcileUtc = DateTime.MinValue; diff --git a/Encelado/src/Encelado.Engine/Baskets/LearningDiskReader.cs b/Encelado/src/Encelado.Engine/Baskets/LearningDiskReader.cs index bec390f..c881af0 100644 --- a/Encelado/src/Encelado.Engine/Baskets/LearningDiskReader.cs +++ b/Encelado/src/Encelado.Engine/Baskets/LearningDiskReader.cs @@ -215,21 +215,29 @@ public static class LearningDiskReader } /// - /// One part of the models of a stopped bot: the file's reading; when the file cannot be read, - /// the last good reading of that part with a warning that says so, or — never read well — - /// null (the caller's starting values) with a warning that says that instead (5.1 review). An - /// absent file is null without a warning: the starting values are what it means. + /// One part of the models as last read well: is the file's reading, null when the + /// file was absent (the starting values are what it means). A part never read well has no such record. /// - private static T? Part(string path, Func parse, bool readBefore, T? lastGood, List warnings) + private sealed record GoodPart(T? Value) + where T : class; + + /// + /// One part of the models of a stopped bot: the file's reading; when the file cannot be read, + /// the last good reading of that part with a warning that says so, or — never read well (no + /// ) — nothing, the caller's starting values, with a warning that says + /// that instead, at this reading and at every next one until it is read well (5.1 review and its + /// second pass). An absent file is a good reading without a value and without a warning. + /// + private static GoodPart? Part(string path, Func parse, GoodPart? lastGood, List warnings) where T : class { (T? value, string? error) = ReadJson(path, parse); if (error is null) { - return value; + return new GoodPart(value); } - warnings.Add(readBefore + warnings.Add(lastGood is not null ? $"{Path.GetFileName(path)} non leggibile ({error}): mostro l'ultima lettura buona" : $"{Path.GetFileName(path)} non leggibile ({error}): nessuna lettura buona prima, mostro i valori iniziali"); return lastGood; @@ -301,7 +309,10 @@ public static class LearningDiskReader }; } - /// What the files of a stopped bot hold, each part kept for the next reading to fall back on. + /// + /// What the files of a stopped bot hold — the parts with the starting values in place of what could not be + /// read — and, for the next reading to fall back on, each part as last read well (null: never read well). + /// private sealed record DiskModels( LearningCapture Capture, OnlineLogistic Logistic, @@ -311,7 +322,19 @@ public static class LearningDiskReader CycleSummary? LastCycle, DatasetSummary? CycleDataset, IReadOnlyDictionary LastRows, - IReadOnlyList Warnings); + IReadOnlyList Warnings) + { + public GoodPart? GoodLogistic { get; init; } + + public GoodPart? GoodMlp { get; init; } + + public GoodPart? GoodBandit { get; init; } + + public GoodPart? GoodState { get; init; } + + /// last_cycle.json was read well (or absent) at least once: is that reading. + public bool CycleReadWell { get; init; } + } /// /// The models of a stopped bot. A file that cannot be read keeps the part last read well @@ -323,12 +346,17 @@ public static class LearningDiskReader { List warnings = []; string models = p.ModelsDir; - bool before = previous is not null; - OnlineLogistic logistic = Part(Path.Combine(models, "logreg_current.json"), OnlineLogistic.FromJson, before, previous?.Logistic, warnings) ?? new OnlineLogistic(LearningFeatures.Count); - SmallMlp? mlp = Part(Path.Combine(models, "mlp_current.json"), SmallMlp.FromJson, before, previous?.Mlp, warnings); - ThompsonBandit bandit = Part(Path.Combine(models, "bandit.json"), static t => ThompsonBandit.FromJson(t), before, previous?.Bandit, warnings) ?? new ThompsonBandit(3, 42); - LearningStateData state = Part(Path.Combine(models, "learning_state.json"), LearningStateFile.Read, before, previous?.State, warnings) ?? new LearningStateData(); - (CycleSummary? last, DatasetSummary? dataset) = LastCycle(Path.Combine(models, "last_cycle.json"), previous, warnings); + + // Each part falls back on its own last good reading, never on the starting values a previous reading showed. + GoodPart? goodLogistic = Part(Path.Combine(models, "logreg_current.json"), OnlineLogistic.FromJson, previous?.GoodLogistic, warnings); + GoodPart? goodMlp = Part(Path.Combine(models, "mlp_current.json"), SmallMlp.FromJson, previous?.GoodMlp, warnings); + GoodPart? goodBandit = Part(Path.Combine(models, "bandit.json"), static t => ThompsonBandit.FromJson(t), previous?.GoodBandit, warnings); + GoodPart? goodState = Part(Path.Combine(models, "learning_state.json"), LearningStateFile.Read, previous?.GoodState, warnings); + OnlineLogistic logistic = goodLogistic?.Value ?? new OnlineLogistic(LearningFeatures.Count); + SmallMlp? mlp = goodMlp?.Value; + ThompsonBandit bandit = goodBandit?.Value ?? new ThompsonBandit(3, 42); + LearningStateData state = goodState?.Value ?? new LearningStateData(); + (CycleSummary? last, DatasetSummary? dataset, bool cycleReadWell) = LastCycle(Path.Combine(models, "last_cycle.json"), previous, warnings); // The labels behind lastNOutcomes, and the labelled count as the training set counts it // (a labelled basket with its entry features): the tick's headline says the same (5.1 review). @@ -349,11 +377,22 @@ public static class LearningDiskReader LearningCapture capture = new(state.Active, state.Champion, state.Version, state.LastCycleUtc, state.LastReport.Length > 0 ? state.LastReport : "nessun ciclo eseguito", state.LabelsFixedUtc, labelledRows, [.. state.Entries.Keys], logistic.Summarize(), mlp?.Summarize(last?.ChallengerWins ?? false), bandit.Summarize(string.Empty, state.LastProposal, false), rolling, last, dataset, []); - return new DiskModels(capture, logistic, mlp, bandit, state, last, dataset, LastRows(Path.Combine(p.LedgerDir, "decisions.jsonl")), warnings); + return new DiskModels(capture, logistic, mlp, bandit, state, last, dataset, LastRows(Path.Combine(p.LedgerDir, "decisions.jsonl")), warnings) + { + GoodLogistic = goodLogistic, + GoodMlp = goodMlp, + GoodBandit = goodBandit, + GoodState = goodState, + CycleReadWell = cycleReadWell, + }; } - /// last_cycle.json: the last cycle and its dataset; when unreadable, the last good reading (or nothing, never read well), with a warning. - private static (CycleSummary? Last, DatasetSummary? Dataset) LastCycle(string path, DiskModels? previous, List warnings) + /// + /// last_cycle.json: the last cycle and its dataset, and whether that is a good reading (an absent file + /// is one, with nothing in it); when unreadable, the last good reading — or nothing, never read well — with a + /// warning that says which. + /// + private static (CycleSummary? Last, DatasetSummary? Dataset, bool ReadWell) LastCycle(string path, DiskModels? previous, List warnings) { string why = string.Empty; try @@ -361,12 +400,12 @@ public static class LearningDiskReader string? text = ReadText(path); if (text is null) { - return (null, null); + return (null, null, true); } if (LearningJson.TryReadCycleFile(text, out CycleSummary? last, out DatasetSummary? dataset)) { - return (last, dataset); + return (last, dataset, true); } } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) @@ -374,14 +413,14 @@ public static class LearningDiskReader why = $" ({ex.Message})"; } - if (previous is not null) + if (previous is { CycleReadWell: true }) { warnings.Add($"last_cycle.json non leggibile{why}: mostro l'ultima lettura buona"); - return (previous.LastCycle, previous.CycleDataset); + return (previous.LastCycle, previous.CycleDataset, true); } warnings.Add($"last_cycle.json non leggibile{why}: l'ultimo ciclo non è mostrato"); - return (null, null); + return (null, null, false); } /// diff --git a/Encelado/src/Encelado.Engine/Baskets/LearningState.cs b/Encelado/src/Encelado.Engine/Baskets/LearningState.cs index 3bcef8e..7bb5caa 100644 --- a/Encelado/src/Encelado.Engine/Baskets/LearningState.cs +++ b/Encelado/src/Encelado.Engine/Baskets/LearningState.cs @@ -861,6 +861,35 @@ public sealed class LearningState : IDisposable return true; } + /// + /// The logistic rebuilt on the corrected ledger, alone (5.1 second review): after the retire, a start on the + /// other account corrected rows of 4.0.0–5.0.0 the logistic had learnt as wins. Only the replay of + /// : the bandit — restarted from its prior by the retire, it never saw those + /// rows —, the challenger (the next cycle trains it on the corrected dataset), the retire mark and the rolling + /// history stay as they are. One line in models_registry.csv says it. + /// + public void ReplayLogistic(DateTime nowUtc, string reason) + { + List replay = BuildDataset(); + lock (_gate) + { + OnlineLogistic logistic = new(LearningFeatures.Count); + foreach (LabelledBasket b in replay) + { + logistic.Update(b.Features, b.Label); + } + + _logistic = logistic; + _logisticSummary = null; + _labelledRows = replay.Count; + string line = string.Create(CultureInfo.InvariantCulture, $"v{_version};{nowUtc:O};logistica;{replay.Count};;;;rifatta;{LearningKnowledge.Clean(reason)}"); + Try("models_registry.csv", () => AppendKnowledge("models_registry.csv", LearningKnowledge.RegistryHeader, [line])); + Save(); + } + + Log.Warn($"apprendimento: logistica rifatta su {replay.Count} basket con le etichette corrette dallo storico eToro ({reason})"); + } + /// Saves everything under the lock (5.1): the owner calls it while it still holds the instance lock, never after. public void Dispose() { diff --git a/Encelado/src/Encelado.Engine/Baskets/RealizedBackfill.cs b/Encelado/src/Encelado.Engine/Baskets/RealizedBackfill.cs index 8138052..efafb61 100644 --- a/Encelado/src/Encelado.Engine/Baskets/RealizedBackfill.cs +++ b/Encelado/src/Encelado.Engine/Baskets/RealizedBackfill.cs @@ -9,6 +9,13 @@ public sealed record BackfillReport(int Checked, int Agreeing, int Corrected, in { public static readonly BackfillReport None = new(0, 0, 0, 0); + /// + /// The rows of 4.0.0–5.0.0 corrected by this run for the first time: until now they carried the close + /// proceeds as the P&L — a "win" — in every label read from them (5.1 second review). The estimates of + /// 5.1 and the rows retried after being unverifiable are not among them: their label was never wrong. + /// + public int CorrectedLegacy { get; init; } + public string Describe() => string.Create(CultureInfo.InvariantCulture, $"{Checked} righe: {Agreeing} concordi, {Corrected} corrette, {Unverifiable} non verificabili"); } @@ -88,7 +95,7 @@ public sealed class RealizedBackfill( // all together, so a note another row took is never given to this one (5.1 review). PositionMap map = PositionMap.Build(_ledger.ReadOrders(), _ledger.ReadLoneLegNotes(), _ledger.ReadEntryFills(), all); - int agree = 0, corrected = 0, unverifiable = 0; + int agree = 0, corrected = 0, unverifiable = 0, legacy = 0; foreach ((BasketOutcomeRow r, bool retry) in rows) { IReadOnlyList ids = map.IdsOf(r, trades, _instrumentOf); @@ -111,13 +118,18 @@ public sealed class RealizedBackfill( else { corrected++; + if (!retry && !r.Motivazione.Contains(SettledMarker, StringComparison.Ordinal)) + { + legacy++; + } + string was = estimate ? "stimato dai prezzi di chiusura" : retry ? "non verificabile finora" : "= proceeds della chiusura (margine restituito + profitto), non il realizzato"; _ledger.PnlCorrection(runId, r, s.GrossUsd, s.NetUsd, true, ids, string.Create(CultureInfo.InvariantCulture, $"P&L registrato {Signed(r.PnlNetUsd)} USD {was}; storico eToro {Signed(s.NetUsd)} USD (netProfit − fees di {ids.Count} posizioni)")); } } - BackfillReport report = new(rows.Count, agree, corrected, unverifiable); + BackfillReport report = new(rows.Count, agree, corrected, unverifiable) { CorrectedLegacy = legacy }; // The note marks how far the check went; a start that only asked again about rows // still unverifiable, and found nothing new, writes nothing at all. diff --git a/Encelado/src/Encelado.Engine/Configuration/EnvironmentImport.cs b/Encelado/src/Encelado.Engine/Configuration/EnvironmentImport.cs index 3089d2b..dab4013 100644 --- a/Encelado/src/Encelado.Engine/Configuration/EnvironmentImport.cs +++ b/Encelado/src/Encelado.Engine/Configuration/EnvironmentImport.cs @@ -2,6 +2,7 @@ using System.Globalization; using System.Text.Json; using System.Text.Json.Nodes; using Encelado.Core.Baskets; +using Encelado.Engine.Baskets; namespace Encelado.Engine.Configuration; @@ -33,7 +34,10 @@ public sealed record ImportOutcome(bool Ran, bool Deferred, IReadOnlyListENCELADO_EXECUTION_MODE+ETORO_ENVIRONMENT, ENCELADO_AUTOSTART=0; a write /// removes the obsolete keys and writes the mode the file meant in place of etoro.environment /// (); -/// TZ and ENCELADO_CONFIRM_LIVE are never imported. +/// TZ and ENCELADO_CONFIRM_LIVE are never imported; +/// which account the 5.0 configuration traded on (), for the +/// engine that moves 5.0's single state file to its account (5.1 review): that file names the +/// execution mode, not the account. /// /// It runs once: <config>/import-5.1.json records what it did (a locked store /// defers it to the next start). From then on every such variable still present is @@ -93,6 +97,11 @@ public static class EnvironmentImport string? envMode = Env("ENCELADO_EXECUTION_MODE"); string? envEnvironment = Env("ETORO_ENVIRONMENT"); + // Whose 5.0's state file is (5.1 review): it names the mode, and 5.0 traded on the account + // etoro.environment named — the variables winning over the file, as in 5.0. Taken now, before + // any save of the settings removes etoro.environment from the file. + LegacyStateOwner? legacyState = LegacyStateOwner.Of(envMode ?? fileModeRaw, envEnvironment ?? fileEnvironmentRaw); + // -------------------------------------------------------------- secrets List secretDeletions = []; if (store.State == SecretStoreState.Locked) @@ -242,12 +251,54 @@ public static class EnvironmentImport if (!deferred) { - WriteMarker(marker, nowUtc, imported, present, notes); + WriteMarker(marker, nowUtc, imported, present, notes, legacyState); } return new ImportOutcome(true, deferred, imported, present, notes, configChanged); } + /// + /// The import's record of the account the 5.0 configuration traded on (), + /// from import-5.1.json in ; null when there is no record (no + /// import yet, a marker written before the record existed, a configuration of 5.1, an unreadable file). + /// + public static LegacyStateOwner? ReadLegacyStateOwner(string configDirectory) + { + if (string.IsNullOrWhiteSpace(configDirectory)) + { + return null; + } + + string path = Path.Combine(configDirectory, MarkerFileName); + try + { + if (!File.Exists(path)) + { + return null; + } + + using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path)); + if (!doc.RootElement.TryGetProperty("legacyState", out JsonElement s) || s.ValueKind != JsonValueKind.Object || + !s.TryGetProperty("mode", out JsonElement mode) || mode.GetString() is not { Length: > 0 } label) + { + return null; + } + + string account = s.TryGetProperty("account", out JsonElement a) && a.ValueKind == JsonValueKind.String ? a.GetString() ?? string.Empty : string.Empty; + return account switch + { + "demo" => new LegacyStateOwner(label, ExecutionMode.Demo), + "live" => new LegacyStateOwner(label, ExecutionMode.Live), + _ when LegacyStateOwner.IsPaper(label) => new LegacyStateOwner("Paper", null), + _ => null, + }; + } + catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException or InvalidOperationException) + { + return null; + } + } + private static ExecutionMode MergedMode(string? mode, string? environment, out bool disagree) { ExecutionModeExtensions.TryParse(mode ?? "Demo", out ExecutionMode parsed); @@ -313,7 +364,7 @@ public static class EnvironmentImport return true; } - private static void WriteMarker(string path, DateTime nowUtc, List imported, IReadOnlyList present, List notes) + private static void WriteMarker(string path, DateTime nowUtc, List imported, IReadOnlyList present, List notes, LegacyStateOwner? legacyState) { try { @@ -327,6 +378,16 @@ public static class EnvironmentImport Array(w, "imported", imported); Array(w, "presentAtImport", present); Array(w, "notes", notes); + if (legacyState is not null) + { + // The 5.0 state file names the mode, not the account: the engine that moves it reads this. + w.WriteStartObject("legacyState"); + w.WriteString("_commento", "Modalità e conto della configurazione 5.0: il file baskets_state.json della 5.0 va al conto su cui quella configurazione operava (Paper: nessuno)."); + w.WriteString("mode", legacyState.Mode); + w.WriteString("account", legacyState.Account is { } account ? account.Account() : string.Empty); + w.WriteEndObject(); + } + w.WriteEndObject(); } diff --git a/Encelado/src/Encelado.Engine/Engine/BotSnapshot.cs b/Encelado/src/Encelado.Engine/Engine/BotSnapshot.cs index 30805c1..c9aea8b 100644 --- a/Encelado/src/Encelado.Engine/Engine/BotSnapshot.cs +++ b/Encelado/src/Encelado.Engine/Engine/BotSnapshot.cs @@ -215,7 +215,10 @@ public sealed record BotSnapshot /// How much of the daily loss budget is used, 0..1; NaN while unknown. public double DailyLossUsedPct { get; init; } = double.NaN; - /// The net equity lost since 00:00 UTC is beyond the daily threshold right now. + /// + /// The net equity lost since 00:00 UTC is beyond the daily threshold right now, or was at the low of a fall of the + /// balance the venue's history has not explained yet (new entries suspended until it is explained). + /// public bool DailyLossHit { get; init; } /// The daily-loss block holds (D-52): no new entries until 00:00 UTC, even if the equity recovered since the hit. diff --git a/Encelado/src/Encelado.Engine/Engine/BotSupervisor.cs b/Encelado/src/Encelado.Engine/Engine/BotSupervisor.cs index 6617284..6c35123 100644 --- a/Encelado/src/Encelado.Engine/Engine/BotSupervisor.cs +++ b/Encelado/src/Encelado.Engine/Engine/BotSupervisor.cs @@ -63,7 +63,11 @@ public sealed class BotSupervisor : IAsyncDisposable /// Counts the starts: the end of an engine's run and a stop change the fields only while they still belong to that engine. private long _generation; - /// The kill-switches, closes and residue closes the engine has now (queued or running): FERMA and the restarts wait for them. + /// + /// The kill-switches, closes and residue closes forwarded now, from the state check until the engine has + /// queued them; from then on the engine counts them itself () until its + /// decision thread is done with them. FERMA and the restarts wait for both. + /// private readonly List _critical = []; /// The learning cycle of a stopped bot (5.1): trained in the background while this process holds the instance lock. @@ -550,14 +554,15 @@ public sealed class BotSupervisor : IAsyncDisposable /// /// Forwards a command to the running engine. A kill-switch, a close or a residue close is - /// tracked while the engine has it: FERMA and the automatic restarts wait for it. A command - /// without an answer in 120 s is answered (it stays in the - /// engine's queue). + /// tracked while the engine has it — not while its caller waits: a caller that goes away (a tab + /// closed, a Telegram poller stopped) or a wait of 120 s that ends leaves it to the engine, and + /// FERMA and the automatic restarts still wait for it. A command without an answer in 120 s is + /// answered (it stays in the engine's queue). /// public async Task ExecuteAsync(EngineCommand command, CancellationToken ct) { ArgumentNullException.ThrowIfNull(command); - bool critical = IsCritical(command); + bool critical = command.IsCritical; IEngine? engine; BotState state; lock (_gate) @@ -588,7 +593,9 @@ public sealed class BotSupervisor : IAsyncDisposable catch (TimeoutException) { Log.Warn($"comando {command.Kind} senza risposta entro 120 s: resta in coda, il motore lo esegue appena è libero"); - return new CommandResult(false, "il motore non ha risposto entro 120 s: il comando resta in coda e lo esegue appena è libero; l'esito sarà nel log") { Code = CommandResult.Timeout }; + return new CommandResult(false, critical + ? $"il motore non ha risposto entro 120 s; il comando ({command.Describe()}) resta in coda o in corso e il motore lo porta a termine: FERMA e i riavvii aspettano che sia concluso; l'esito sarà nel log" + : "il motore non ha risposto entro 120 s: il comando resta in coda e lo esegue appena è libero; l'esito sarà nel log") { Code = CommandResult.Timeout }; } finally { @@ -711,21 +718,11 @@ public sealed class BotSupervisor : IAsyncDisposable } } - /// The first critical command in hand, described; held. - private string? CriticalInProgress() => _critical.Count > 0 ? Describe(_critical[0]) : null; - - /// The commands that send closes to the venue: a stop or a restart must not cut them in half. - private static bool IsCritical(EngineCommand c) => - c.Kind is EngineCommandKind.KillSwitch or EngineCommandKind.Close or EngineCommandKind.CloseResidue || - (c.Kind == EngineCommandKind.Bonifica && c.Argument.StartsWith("close:", StringComparison.OrdinalIgnoreCase)); - - private static string Describe(EngineCommand c) => c.Kind switch - { - EngineCommandKind.KillSwitch => "kill-switch", - EngineCommandKind.Close => $"chiusura di {c.Argument}", - EngineCommandKind.CloseResidue => "chiusura dei residui", - _ => "chiusura di una gamba orfana (bonifica)", - }; + /// + /// The first critical command in hand, described: one being forwarded, or one the engine has queued or + /// running (5.1 second review: whoever stopped waiting for it); held. + /// + private string? CriticalInProgress() => _critical.Count > 0 ? _critical[0].Describe() : _engine?.CriticalCommand; // ----------------------------------------------------------------------- // The learning cycle on demand (5.1, decision L2) diff --git a/Encelado/src/Encelado.Engine/Engine/EngineView.cs b/Encelado/src/Encelado.Engine/Engine/EngineView.cs index dcc25b7..16b9ff5 100644 --- a/Encelado/src/Encelado.Engine/Engine/EngineView.cs +++ b/Encelado/src/Encelado.Engine/Engine/EngineView.cs @@ -149,7 +149,10 @@ public sealed record FundsView public double DailyLossUsedPct { get; init; } = double.NaN; - /// The net equity lost since 00:00 UTC is beyond the daily threshold right now. + /// + /// The net equity lost since 00:00 UTC is beyond the daily threshold right now, or was at the low of a fall of the + /// balance the venue's history has not explained yet (new entries suspended until it is explained). + /// public bool DailyLossHit { get; init; } /// The daily-loss block holds until 00:00 UTC (D-52): the rule was hit today, even if the equity recovered since. diff --git a/Encelado/src/Encelado.Engine/Engine/IEngine.cs b/Encelado/src/Encelado.Engine/Engine/IEngine.cs index 9e5e6a3..e8e8d77 100644 --- a/Encelado/src/Encelado.Engine/Engine/IEngine.cs +++ b/Encelado/src/Encelado.Engine/Engine/IEngine.cs @@ -93,6 +93,24 @@ public sealed record EngineCommand(EngineCommandKind Kind, string Argument = "", /// The argument of that leaves the foreign positions alone, whatever risk.closeForeignOnKill says. public const string KillBotOnly = "solo-bot"; + /// + /// The commands that send closes to the venue — the kill-switch, a basket's close, the residue's close, + /// an orphan's close in the bonifica: a stop or a restart must not cut them in half. + /// + public bool IsCritical => + Kind is EngineCommandKind.KillSwitch or EngineCommandKind.Close or EngineCommandKind.CloseResidue || + (Kind == EngineCommandKind.Bonifica && Argument.StartsWith("close:", StringComparison.OrdinalIgnoreCase)); + + /// A critical command as the operator reads it ("kill-switch", "chiusura di EURUSD/USDCHF"). + public string Describe() => Kind switch + { + EngineCommandKind.KillSwitch => "kill-switch", + EngineCommandKind.Close => $"chiusura di {Argument}", + EngineCommandKind.CloseResidue => "chiusura dei residui", + EngineCommandKind.Bonifica => "chiusura di una gamba orfana (bonifica)", + _ => Kind.ToString(), + }; + /// /// The caller's choice about the foreign positions in a kill-switch argument: true (close them), /// false (leave them), null when it made none and the setting risk.closeForeignOnKill decides @@ -139,6 +157,14 @@ public interface IEngine : IAsyncDisposable /// bool LoopStarted => true; + /// + /// The first critical command () the engine has in hand, queued or + /// running on its decision thread, described for the operator; null when none (5.1 second review). It + /// counts until the decision thread is done with it — or the run ends without it — whatever its caller + /// does: a closed tab, a stopped Telegram poller or a wait of 120 s over never free FERMA in the middle. + /// + string? CriticalCommand => null; + /// /// The 5.0 picture for the console and Telegram, adapted from : /// building it reads nothing the decision thread writes. is the diff --git a/Encelado/src/Encelado.Engine/Settings/AccountActivity.cs b/Encelado/src/Encelado.Engine/Settings/AccountActivity.cs index e366562..0ce178a 100644 --- a/Encelado/src/Encelado.Engine/Settings/AccountActivity.cs +++ b/Encelado/src/Encelado.Engine/Settings/AccountActivity.cs @@ -41,7 +41,10 @@ public sealed record AccountActivity(int OpenBaskets, int PendingBaskets, int Pe /// The engine has not read its state yet, or the state on disk cannot be read: busy, the prudent answer. public bool Unknown { get; init; } - public bool Busy => OpenBaskets + PendingBaskets + PendingOrders + InFlight + ErrorLegs + OrphanLegs + PendingSettlements > 0 || Unknown; + /// The running engine could not read the account's positions for the guard: what is on the account is not known (busy). + public bool AccountUnread { get; init; } + + public bool Busy => OpenBaskets + PendingBaskets + PendingOrders + InFlight + ErrorLegs + OrphanLegs + PendingSettlements > 0 || Unknown || AccountUnread; /// What is still open, in Italian, naming only what there is. public string Describe() @@ -59,6 +62,11 @@ public sealed record AccountActivity(int OpenBaskets, int PendingBaskets, int Pe parts.Add("uno stato non ancora letto o non leggibile"); } + if (AccountUnread) + { + parts.Add("le posizioni del conto non lette da eToro (non si sa cosa c'è)"); + } + return parts.Count == 0 ? "niente in sospeso" : string.Join(", ", parts); void Add(int n, string one, string many) @@ -130,16 +138,17 @@ public sealed record AccountActivity(int OpenBaskets, int PendingBaskets, int Pe /// /// From the files a stopped engine left for : its own state /// (: open and pending baskets, closes waiting - /// for the history, the residue of a kill-switch) and the orders of that account without an - /// outcome in data/state/pending_orders.json. An unreadable file counts as busy: - /// refusing a switch is the prudent answer. + /// for the history, the residue of a kill-switch — the single file of 5.0 counted for the + /// account says it was written on) and the orders of that account + /// without an outcome in data/state/pending_orders.json. An unreadable file counts as + /// busy: refusing a switch is the prudent answer. /// - public static AccountActivity FromDisk(string dataPath, ExecutionMode account) + public static AccountActivity FromDisk(string dataPath, ExecutionMode account, LegacyStateOwner? legacyOwner = null) { ArgumentException.ThrowIfNullOrWhiteSpace(dataPath); int open = 0, pending = 0, settlements = 0, residue = 0; bool unknown = false; - if (AccountStateFiles.ReadablePathFor(dataPath, account) is { } state) + if (AccountStateFiles.ReadablePathFor(dataPath, account, legacyOwner) is { } state) { try { diff --git a/Encelado/src/Encelado.Engine/Settings/SettingsRuntime.cs b/Encelado/src/Encelado.Engine/Settings/SettingsRuntime.cs index a059254..400a79a 100644 --- a/Encelado/src/Encelado.Engine/Settings/SettingsRuntime.cs +++ b/Encelado/src/Encelado.Engine/Settings/SettingsRuntime.cs @@ -307,7 +307,7 @@ public sealed class SettingsRuntime { // Stopped (or stopped since): the files of the account in use decide. running = false; - AccountActivity activity = AccountActivity.FromDisk(Config.Run.DataPath, before); + AccountActivity activity = DiskActivity(before); if (activity.Busy) { return Refused($"{what} è rifiutato: sul conto {Label(before)} c'è ancora qualcosa in sospeso ({activity.Describe()}). {activity.Advice(engineRunning: false)} (niente è stato salvato)."); @@ -339,7 +339,7 @@ public sealed class SettingsRuntime string? leftBehind = null; RestartResult rr = await RestartCoreAsync(confirmed, $"impostazioni salvate: {paths}", () => { - AccountActivity left = AccountActivity.FromDisk(Config.Run.DataPath, before); + AccountActivity left = DiskActivity(before); if (!left.Busy) { return null; @@ -645,6 +645,13 @@ public sealed class SettingsRuntime private Task RestartCoreAsync(bool liveConfirmed, string reason, Func? afterStop = null) => Supervisor.RestartAsync(reason, Config.Run.Mode.IsLive() && liveConfirmed, () => afterStop?.Invoke() ?? StartRefusal(liveConfirmed)); + /// + /// What the files say is still in hand on ; the single state file of 5.0 counts + /// for the account the import found the 5.0 configuration trading on (5.1 review). + /// + private AccountActivity DiskActivity(ExecutionMode account) => + AccountActivity.FromDisk(Config.Run.DataPath, account, EnvironmentImport.ReadLegacyStateOwner(Path.GetDirectoryName(Path.GetFullPath(ConfigPath)) ?? string.Empty)); + /// What a stopped engine left on , described; null when it is flat or an engine runs again. private string? StoppedAccountActivity(ExecutionMode account) { @@ -653,7 +660,7 @@ public sealed class SettingsRuntime return null; } - AccountActivity left = AccountActivity.FromDisk(Config.Run.DataPath, account); + AccountActivity left = DiskActivity(account); return left.Busy ? left.Describe() : null; } @@ -708,6 +715,10 @@ public sealed class SettingsRuntime /// Proves a pair of keys on its own account (profile and balance) and stores it /// encrypted. When it is the account the running engine trades on, the engine is /// restarted to take them (Live: only with the phrase, asked before anything is saved). + /// The check takes up to 25 s outside the lock: whether to restart is decided again under + /// the lock, on the account in use and the engine running then (5.1 second review) — keys + /// that are no longer the running account's restart nothing, and a Live engine is never + /// restarted without the phrase of this save. /// public async Task SaveKeysAsync(string? account, string? apiKey, string? userKey, string? confirm, CancellationToken ct) { @@ -733,7 +744,8 @@ public sealed class SettingsRuntime bool confirmed = LiveConfirmation.IsConfirmed(confirm); if (active && Supervisor.IsRunning) { - // Asked before the keys are even checked: nothing is saved until the answer is yes. + // Asked before the keys are even checked: nothing is saved until the answer is yes. An early answer + // only — the restart itself is decided again under the lock, after the check. if (Supervisor.CommandInProgress is { } busy) { return new SecretActionResult(false, $"{busy} in corso: le chiavi del conto in uso riavviano il motore e lo interromperebbero a metà; salvale quando è concluso (niente è stato salvato)", SettingsResult.RestartRefused, 409); @@ -767,9 +779,12 @@ public sealed class SettingsRuntime await _lock.WaitAsync(ct).ConfigureAwait(false); try { + // Everything read again now, under the lock (5.1 second review): a FERMA, an AVVIA or a change of + // account may have come while eToro checked the keys. Whose keys they are is the account in use now. + bool activeNow = Config.Run.Mode.IsLive() != demo; Secrets.SaveEtoro(demo, new EtoroKeys(api, user, DateTime.UtcNow)); Changed(); - if (active) + if (activeNow) { _hooks.InvalidateHistory?.Invoke(); } @@ -777,15 +792,15 @@ public sealed class SettingsRuntime Log.Info($"chiavi eToro del conto {label} verificate ({who}, {KeyStores.Mask(api)}) e salvate cifrate"); string message = $"chiavi del conto {label} verificate: {who}; salvate cifrate"; - // Read again now: a FERMA or an AVVIA may have come while eToro checked the keys. - if (!(active && Supervisor.IsRunning)) + if (!(activeNow && Supervisor.IsRunning)) { return new SecretActionResult(true, message) { Detail = who }; } - if (!demo && !confirmed) + if (Config.Run.Mode.IsLive() && !confirmed) { - // Started in Live meanwhile, without the phrase for this save: saved, not restarted. + // The engine to restart is Live (started, or switched to Live, meanwhile) and this save carried no + // phrase: saved, not restarted — a restart would leave the real account's engine stopped. return new SecretActionResult(true, $"{message}; il motore in Live non è stato riavviato: per usarle premi FERMA e poi AVVIA con {LiveConfirmation.Phrase}") { Detail = who }; } @@ -994,7 +1009,7 @@ public sealed class SettingsRuntime return new SecretActionResult(false, "ferma il motore prima di ripristinare la configurazione", HttpStatus: 409); } - if (Config.Run.Mode.IsLive() && AccountActivity.FromDisk(Config.Run.DataPath, ExecutionMode.Live) is { Busy: true } live) + if (Config.Run.Mode.IsLive() && DiskActivity(ExecutionMode.Live) is { Busy: true } live) { return new SecretActionResult(false, $"il ripristino riporta il conto a Demo, ma sul conto reale c'è ancora qualcosa in sospeso ({live.Describe()}). {live.Advice(engineRunning: false)}", HttpStatus: 409); } diff --git a/Encelado/src/Encelado.Server/Web/AuthBackoff.cs b/Encelado/src/Encelado.Server/Web/AuthBackoff.cs index 760c81a..86ecafb 100644 --- a/Encelado/src/Encelado.Server/Web/AuthBackoff.cs +++ b/Encelado/src/Encelado.Server/Web/AuthBackoff.cs @@ -17,9 +17,10 @@ internal enum AuthVerdict } /// -/// The price of a wrong password (5.1 review), the same for every way one arrives: the login form, the -/// Authorization: Bearer header and the session cookie — the cookie is derived from the password -/// with nothing secret beside it, so it can be computed for every guess and is a guess too. +/// The price of a wrong password (5.1 review), the same for both ways one arrives: the login form and the +/// Authorization: Bearer header. The session cookie is not one of them (5.1 second review): it holds the +/// server's own secret (), so it cannot be computed from a guess — a valid one goes in +/// without touching the count, even while its address waits, and a wrong one is simply not signed in. /// /// Per client address (an IPv6 client by its /64, which one host can fill with addresses at will): after /// a wrong password the address waits one second, then two, four, eight, sixteen, at most thirty for each @@ -28,8 +29,9 @@ internal enum AuthVerdict /// right one included, or a lucky guess sent in parallel with many wrong ones would stand out — and those /// requests get 429 with Retry-After. Checking and recording happen under one lock, so parallel /// guesses get one check per wait. A right password clears the count; ten quiet minutes forget it. -/// Another address is never slowed: a guesser on the network cannot lock the operator out of the -/// kill-switch from their own computer (only behind a proxy that hides every address behind its own). +/// Another address is never slowed, and a signed-in page never is: a guesser on the network cannot lock +/// the operator out of the kill-switch, even from behind the same NAT or proxy (a new login from there +/// waits like any password). /// /// internal sealed class AuthBackoff(TimeProvider? time = null) diff --git a/Encelado/src/Encelado.Server/Web/SessionKey.cs b/Encelado/src/Encelado.Server/Web/SessionKey.cs new file mode 100644 index 0000000..d574bae --- /dev/null +++ b/Encelado/src/Encelado.Server/Web/SessionKey.cs @@ -0,0 +1,78 @@ +using System.Security.Cryptography; + +namespace Encelado.Server.Web; + +/// +/// The server's own secret in the session cookie (5.1 second review): 32 random bytes in +/// <config>/session.key, written once — atomically, readable by the owner only — and read +/// at every start, so a session survives a restart of the container. With it the cookie cannot be +/// computed from a guessed password any more: a wrong cookie (a tab left open over a password +/// change, a key deleted) is simply not signed in, never a guess that costs its address a wait, and +/// a valid one is never kept out by the wait a guesser on the same address brought on it. Deleting +/// the file closes every session; so does a change of the password. +/// +internal static class SessionKey +{ + public const string FileName = "session.key"; + + public const int Size = 32; + + /// + /// The key of , created when missing (or damaged: every session then closes). + /// A folder that can be neither read nor written gives a key for this process only, and + /// says so: the sessions then end with the process. Never throws. + /// + public static byte[] LoadOrCreate(string configDirectory, out string? problem) + { + ArgumentException.ThrowIfNullOrWhiteSpace(configDirectory); + problem = null; + string path = Path.Combine(configDirectory, FileName); + try + { + if (File.Exists(path)) + { + byte[] key = File.ReadAllBytes(path); + if (key.Length == Size) + { + return key; + } + + problem = $"{FileName} danneggiato: ne creo uno nuovo, le sessioni aperte si chiudono (serve un nuovo accesso)"; + } + + byte[] fresh = RandomNumberGenerator.GetBytes(Size); + Write(path, fresh); + return fresh; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + problem = $"{FileName} non leggibile né scrivibile in {configDirectory} ({ex.Message}): le sessioni valgono fino al prossimo riavvio"; + return RandomNumberGenerator.GetBytes(Size); + } + } + + private static void Write(string path, byte[] key) + { + string? directory = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(directory)) + { + Directory.CreateDirectory(directory); + } + + string temporary = $"{path}.{Guid.NewGuid():N}.tmp"; + File.WriteAllBytes(temporary, key); + if (!OperatingSystem.IsWindows()) + { + try + { + File.SetUnixFileMode(temporary, UnixFileMode.UserRead | UnixFileMode.UserWrite); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or PlatformNotSupportedException) + { + // Best effort, as for secrets.key: the folder is the operator's /config. + } + } + + File.Move(temporary, path, overwrite: true); + } +} diff --git a/Encelado/src/Encelado.Server/Web/WebHost.cs b/Encelado/src/Encelado.Server/Web/WebHost.cs index e17b60c..6d43eb6 100644 --- a/Encelado/src/Encelado.Server/Web/WebHost.cs +++ b/Encelado/src/Encelado.Server/Web/WebHost.cs @@ -90,13 +90,15 @@ public sealed class WebContext /// /// Access (5.1, decisions C1-C2): the interface password (ENCELADO_PASSWORD, the /// container's only variable) is asked once on the login page; the browser then carries -/// the session cookie encelado_session — an HMAC derived from the password, never -/// the password itself, so changing the password closes every session. Scripts may send +/// the session cookie encelado_session — an HMAC of the password and of the server's +/// own secret (, 5.1 second review), never the password itself, so +/// changing the password closes every session. Scripts may send /// Authorization: Bearer <password>. Every comparison is constant-time, and a -/// wrong password — by the form, the header or the cookie — costs its address a wait that -/// doubles up to thirty seconds (, 5.1 review). The network sees the -/// interface only in the container or with --listen-all, and only with a password; -/// without one the server is on localhost and asks for nothing (development). +/// wrong password — by the form or the header — costs its address a wait that doubles up to +/// thirty seconds (, 5.1 review). A cookie is no password: a valid one +/// goes in even while its address waits, a wrong one is simply not signed in, at once. The +/// network sees the interface only in the container or with --listen-all, and only with +/// a password; without one the server is on localhost and asks for nothing (development). /// /// /// Requests from elsewhere (5.1 review, ): a write must be JSON and come @@ -136,16 +138,19 @@ public static class WebHost public static bool ListensOnTheNetwork(bool passwordSet, bool inContainer, bool listenAllFlag) => passwordSet && (inContainer || listenAllFlag); /// - /// The session cookie's value for a password: Base64Url(HMAC-SHA256(key = SHA-256("encelado/cookie/v1" ‖ password), "session")). + /// The session cookie's value for a password and the server's secret (): + /// Base64Url(HMAC-SHA256(key = SHA-256("encelado/cookie/v2" ‖ secret ‖ password), "session")). + /// Without the secret it cannot be computed from a guessed password (5.1 second review: v1 had only the password in it). /// - public static string SessionValue(string password) + public static string SessionValue(ReadOnlySpan serverSecret, string password) { ArgumentNullException.ThrowIfNull(password); - byte[] prefix = "encelado/cookie/v1"u8.ToArray(); + ReadOnlySpan prefix = "encelado/cookie/v2"u8; byte[] secret = Encoding.UTF8.GetBytes(password); - byte[] material = new byte[prefix.Length + secret.Length]; - prefix.CopyTo(material, 0); - secret.CopyTo(material, prefix.Length); + byte[] material = new byte[prefix.Length + serverSecret.Length + secret.Length]; + prefix.CopyTo(material); + serverSecret.CopyTo(material.AsSpan(prefix.Length)); + secret.CopyTo(material.AsSpan(prefix.Length + serverSecret.Length)); byte[] key = SHA256.HashData(material); byte[] mac = HMACSHA256.HashData(key, "session"u8); CryptographicOperations.ZeroMemory(material); @@ -192,10 +197,23 @@ public static class WebHost SampleLogFeeder.Start(ctx.Log, sample, app.Lifetime.ApplicationStopping); } + // The session's value, with the server's own secret kept beside the configuration (no password: no session, no file). + string session = string.Empty; + if (password.Length > 0) + { + byte[] secret = SessionKey.LoadOrCreate(Path.GetDirectoryName(Path.GetFullPath(ctx.ConfigPath)) ?? ".", out string? keyProblem); + session = SessionValue(secret, password); + CryptographicOperations.ZeroMemory(secret); + if (keyProblem is not null) + { + EngineLog.Warn($"sessioni dell'interfaccia: {keyProblem}"); + } + } + AuthBackoff backoff = new(); app.Use(RequestGuard(hasPassword: password.Length > 0)); - app.Use(Auth(password, backoff)); - MapLogin(app, password, backoff); + app.Use(Auth(password, session, backoff)); + MapLogin(app, password, session, backoff); MapApi(app, ctx, hub); SettingsApi.Map(app, ctx); MapStatic(app); @@ -213,14 +231,16 @@ public static class WebHost path.StartsWith("/img/", StringComparison.Ordinal); /// - /// The session cookie or the Bearer password, checked through the address's : a - /// request that carries neither is simply not signed in (401 or the login page, at once); one that carries - /// a wrong one is answered only when its address's wait is over, and while it waits nothing of that - /// address is checked (429). + /// The session cookie, then the Bearer password. A valid cookie goes in at once and touches no count: with the + /// server's secret in it, it cannot be computed from a guessed password, so it is never a guess — and never + /// kept out by the wait a guesser on the same address (a NAT, an IPv6 /64, a proxy) brought on it (5.1 second + /// review: a tab left open over a password change kept its address waiting, the right password included). A + /// wrong cookie alone is simply not signed in (401 or the login page, at once). The Bearer password goes + /// through the address's : a wrong one is answered only when the wait is over, and + /// while it waits no password of that address is checked (429). /// - private static Func Auth(string password, AuthBackoff backoff) + private static Func Auth(string password, string session, AuthBackoff backoff) { - string session = password.Length > 0 ? SessionValue(password) : string.Empty; return async (http, next) => { string path = http.Request.Path.Value ?? "/"; @@ -230,12 +250,16 @@ public static class WebHost return; } - string? cookie = http.Request.Cookies.TryGetValue(CookieName, out string? c) && c.Length > 0 ? c : null; - string? bearer = http.Request.Headers.Authorization.ToString() is { Length: > 7 } auth && auth.StartsWith("Bearer ", StringComparison.Ordinal) && auth[7..].Trim() is { Length: > 0 } b ? b : null; - if (cookie is not null || bearer is not null) + if (http.Request.Cookies.TryGetValue(CookieName, out string? cookie) && cookie.Length > 0 && Constant(cookie, session)) { - AuthVerdict verdict = backoff.Check(AuthBackoff.ClientKey(http.Connection.RemoteIpAddress), - () => (cookie is not null && Constant(cookie, session)) | (bearer is not null && Constant(bearer, password)), out TimeSpan wait); + await next(http).ConfigureAwait(false); + return; + } + + string? bearer = http.Request.Headers.Authorization.ToString() is { Length: > 7 } auth && auth.StartsWith("Bearer ", StringComparison.Ordinal) && auth[7..].Trim() is { Length: > 0 } b ? b : null; + if (bearer is not null) + { + AuthVerdict verdict = backoff.Check(AuthBackoff.ClientKey(http.Connection.RemoteIpAddress), () => Constant(bearer, password), out TimeSpan wait); if (verdict == AuthVerdict.Ok) { await next(http).ConfigureAwait(false); @@ -248,7 +272,7 @@ public static class WebHost return; } - await Task.Delay(wait, http.RequestAborted).ConfigureAwait(false); + await WaitOutAsync(wait, http.RequestAborted).ConfigureAwait(false); } if (path.StartsWith("/api/", StringComparison.Ordinal)) @@ -262,6 +286,15 @@ public static class WebHost }; } + /// A timer may fire up to one tick of the system clock (about 16 ms on Windows) before the time the backoff reads. + private static readonly TimeSpan TimerSlack = TimeSpan.FromMilliseconds(50); + + /// + /// Holds a wrong answer until its address's wait is really over (5.1 second review): a person who tries again + /// the moment "Password errata." appears is never told to wait once more. + /// + private static Task WaitOutAsync(TimeSpan wait, CancellationToken ct) => Task.Delay(wait + TimerSlack, ct); + /// 429 while the address waits after a wrong password: JSON under /api/, the login page with the message elsewhere. private static async Task TooManyAsync(HttpContext http, string path, TimeSpan wait) { @@ -397,7 +430,7 @@ public static class WebHost // Login, static files // ----------------------------------------------------------------------- - private static void MapLogin(WebApplication app, string password, AuthBackoff backoff) + private static void MapLogin(WebApplication app, string password, string session, AuthBackoff backoff) { app.MapPost("/login", async http => { @@ -408,11 +441,11 @@ public static class WebHost TimeSpan wait = FailedLoginDelay; if (password.Length > 0 && given.Length > 0) { - // The same backoff as the Bearer header and the cookie: one wait per address, whatever the door. + // The same backoff as the Bearer header: one wait per address, whichever door the password came by. switch (backoff.Check(AuthBackoff.ClientKey(http.Connection.RemoteIpAddress), () => Constant(given, password), out wait)) { case AuthVerdict.Ok: - http.Response.Cookies.Append(CookieName, SessionValue(password), new CookieOptions { HttpOnly = true, SameSite = SameSiteMode.Strict, IsEssential = true, Path = "/", MaxAge = TimeSpan.FromDays(30) }); + http.Response.Cookies.Append(CookieName, session, new CookieOptions { HttpOnly = true, SameSite = SameSiteMode.Strict, IsEssential = true, Path = "/", MaxAge = TimeSpan.FromDays(30) }); http.Response.Redirect("/"); return; case AuthVerdict.Blocked: @@ -421,7 +454,7 @@ public static class WebHost } } - await Task.Delay(wait, http.RequestAborted).ConfigureAwait(false); + await WaitOutAsync(wait, http.RequestAborted).ConfigureAwait(false); http.Response.StatusCode = 401; await Text(http, LoginPageWithError(password.Length > 0 ? "Password errata." : "Questo server non ha una password: apri direttamente la pagina."), "text/html; charset=utf-8").ConfigureAwait(false); }); diff --git a/Encelado/src/Encelado.Server/Web/wwwroot/js/stream.js b/Encelado/src/Encelado.Server/Web/wwwroot/js/stream.js index 39c83e9..aea1f7b 100644 --- a/Encelado/src/Encelado.Server/Web/wwwroot/js/stream.js +++ b/Encelado/src/Encelado.Server/Web/wwwroot/js/stream.js @@ -18,7 +18,7 @@ export function startStream(url, snapshotUrl) { const probe = () => { // a failing stream may mean an expired session if (Date.now() - lastProbe < 10000) return; lastProbe = Date.now(); - api(snapshotUrl, { quiet: true }); // a 401 redirects to /login + api(snapshotUrl, { quiet: true }); // a 401 (or a 429) redirects to /login }; const poll = async () => { // no EventSource: read the snapshot every 2 s if (!document.hidden) { diff --git a/Encelado/src/Encelado.Server/Web/wwwroot/js/util.js b/Encelado/src/Encelado.Server/Web/wwwroot/js/util.js index 3bdd8d8..e3051fa 100644 --- a/Encelado/src/Encelado.Server/Web/wwwroot/js/util.js +++ b/Encelado/src/Encelado.Server/Web/wwwroot/js/util.js @@ -264,7 +264,8 @@ export async function track(promise) { // ── API ───────────────────────────────────────────────────────────────────────────────────────── /** * One call to the bot. Returns { ok, status, data, etag, notModified }; never throws for HTTP - * errors (network failures give status 0). A 401 sends the browser to the login page. + * errors (network failures give status 0). A 401 — or a 429, a page that cannot sign in while its + * address waits after a wrong password — sends the browser to the login page, so it stops asking. * Every call that changes state (any method but GET/HEAD) says Content-Type: application/json, with * or without a body: the server refuses the others (415), so a cross-site form cannot post here. */ @@ -279,7 +280,7 @@ export async function api(path, { method = 'GET', body, etag, quiet = false } = } catch (e) { return { ok: false, status: 0, data: { ok: false, message: 'Il bot non risponde: ' + (e.message || e) } }; } - if (r.status === 401) { location.href = '/login'; return { ok: false, status: 401, data: { ok: false, message: 'Sessione scaduta' } }; } + if (r.status === 401 || r.status === 429) { location.href = '/login'; return { ok: false, status: r.status, data: { ok: false, message: 'Sessione scaduta' } }; } if (r.status === 304) return { ok: true, status: 304, notModified: true, data: null, etag }; const text = await r.text(); let data; diff --git a/Encelado/tests/Encelado.Tests/AccountStateTests.cs b/Encelado/tests/Encelado.Tests/AccountStateTests.cs index bec837e..96ab6c0 100644 --- a/Encelado/tests/Encelado.Tests/AccountStateTests.cs +++ b/Encelado/tests/Encelado.Tests/AccountStateTests.cs @@ -30,6 +30,9 @@ internal sealed class AccountVenue : IBroker /// The orders asked about, by the venue's id. public List Lookups { get; } = []; + /// When set, the positions cannot be read (the venue answers with an error). + public bool PositionsFail { get; set; } + public BrokerEnvironment Environment => BrokerEnvironment.Demo; public string Name => "conto di prova"; @@ -47,7 +50,8 @@ internal sealed class AccountVenue : IBroker public Task GetAccountAsync(CancellationToken ct) => Task.FromResult(new AccountSnapshot(DateTime.UtcNow, "USD", Balance, Equity, Equity, 0, Equity - Balance)); - public Task> GetPositionsAsync(CancellationToken ct) => Task.FromResult>([.. Positions]); + public Task> GetPositionsAsync(CancellationToken ct) => + PositionsFail ? Task.FromException>(new BrokerException("503 Service Unavailable")) : Task.FromResult>([.. Positions]); public Task OpenAsync(OrderRequest request, CancellationToken ct) => throw new NotSupportedException("nessun ordine nei test del conto"); @@ -299,19 +303,21 @@ public sealed class AccountStateTests : TempFolderTests [Fact] public void AMigrationKeepsTheMoreRecentStateAndNeverDeletesTheOther() { + // Single files of the first 5.1 builds (they have pendingSettlements): their mode is the account. DateTime now = DateTime.UtcNow; WriteState(StateOf(ExecutionMode.Live), new JsonObject { ["savedUtc"] = now.AddHours(-1).ToString("O", CultureInfo.InvariantCulture), ["mode"] = "Live", ["peakNetEquity"] = 1 }); - WriteState(Legacy, new JsonObject { ["savedUtc"] = now.ToString("O", CultureInfo.InvariantCulture), ["mode"] = "Live", ["peakNetEquity"] = 2 }); + WriteState(Legacy, new JsonObject { ["savedUtc"] = now.ToString("O", CultureInfo.InvariantCulture), ["mode"] = "Live", ["peakNetEquity"] = 2, ["pendingSettlements"] = new JsonArray() }); - string? note = AccountStateFiles.MigrateLegacy(DataPath, ExecutionMode.Demo); + LegacyMigration? note = AccountStateFiles.MigrateLegacy(DataPath, ExecutionMode.Demo); Assert.NotNull(note); + Assert.True(note.Taken); Assert.Equal(2, Read(StateOf(ExecutionMode.Live)).GetProperty("peakNetEquity").GetDouble()); Assert.Equal(1, Read(StateOf(ExecutionMode.Live) + ".precedente").GetProperty("peakNetEquity").GetDouble()); Assert.Equal(2, Read(Legacy + ".migrato").GetProperty("peakNetEquity").GetDouble()); // An older single file (a return to a previous version) leaves the account's own file as it is. - WriteState(Legacy, new JsonObject { ["savedUtc"] = now.AddDays(-1).ToString("O", CultureInfo.InvariantCulture), ["mode"] = "Live", ["peakNetEquity"] = 3 }); + WriteState(Legacy, new JsonObject { ["savedUtc"] = now.AddDays(-1).ToString("O", CultureInfo.InvariantCulture), ["mode"] = "Live", ["peakNetEquity"] = 3, ["pendingSettlements"] = new JsonArray() }); Assert.NotNull(AccountStateFiles.MigrateLegacy(DataPath, ExecutionMode.Demo)); Assert.Equal(2, Read(StateOf(ExecutionMode.Live)).GetProperty("peakNetEquity").GetDouble()); Assert.False(File.Exists(Legacy)); @@ -319,6 +325,158 @@ public sealed class AccountStateTests : TempFolderTests Assert.Null(AccountStateFiles.MigrateLegacy(DataPath, ExecutionMode.Demo)); } + // ----------------------------------------------------------------------- + // The single file of 5.0 names the mode, not the account (second review) + // ----------------------------------------------------------------------- + + /// What 5.0 wrote: mode = the execution mode, no pendingSettlements, no lastPositionIds. + private static JsonObject State50(string mode, double balance, JsonArray? baskets = null) => new() + { + ["savedUtc"] = DateTime.UtcNow.AddDays(-3).ToString("O", CultureInfo.InvariantCulture), + ["runId"] = "20260920-120000-abcdef", + ["mode"] = mode, + ["peakEquity"] = balance, + ["peakNetEquity"] = balance, + ["cumulativeCashFlow"] = 0, + ["lastBalance"] = balance, + ["lastBalanceUtc"] = DateTime.UtcNow.AddDays(-3).ToString("O", CultureInfo.InvariantCulture), + ["sessionDate"] = DateTime.UtcNow.AddDays(-3).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + ["dayStartEquity"] = balance, + ["todayRealized"] = 0, + ["killSwitched"] = false, + ["equityStopped"] = false, + ["haltReason"] = string.Empty, + ["haltResidue"] = new JsonArray(), + ["baskets"] = baskets ?? new JsonArray(), + ["pendingEntries"] = new JsonArray(), + }; + + /// The first start of 5.1 over a 5.0 configuration: the one-time import records which account it traded on. + private void Import50(string mode, string environment) + { + string configPath = Path.Combine(Root, "encelado.json"); + JsonObject config50 = new() + { + ["etoro"] = new JsonObject { ["environment"] = environment }, + ["run"] = new JsonObject { ["executionMode"] = mode, ["allowLive"] = true }, + }; + File.WriteAllText(configPath, config50.ToJsonString(), new UTF8Encoding(false)); + ImportOutcome import = EnvironmentImport.Run(configPath, new SecretStore(Root, "password", 1_000), static _ => null, DateTime.UtcNow); + Assert.True(import.Ran); + } + + /// A real account of 1 000 USD whose engine starts after the upgrade: it must not book the demo account's balance as a withdrawal. + private async Task StartLiveOnARealAccountOf1000() + { + AccountVenue real = new() { Balance = 1_000, Equity = 1_000 }; + BasketEngine live = BasketEngine.OverVenue(Config(ExecutionMode.Live), real, startConfirmed: true); + live.LoadState(); + await live.StartupEquityAsync(CancellationToken.None); + live.SaveState(); + await live.DisposeAsync(); + return Read(StateOf(ExecutionMode.Live)); + } + + [Fact] + public async Task AFiftyLiveFileOfTheDemoAccountStaysWithTheDemoAccount() + { + // 5.0 allowed Live beside etoro.environment = demo: that engine traded the DEMO account and saved mode "Live". + Import50("Live", "demo"); + Assert.Equal(new LegacyStateOwner("Live", ExecutionMode.Demo), EnvironmentImport.ReadLegacyStateOwner(Root)); + WriteState(Legacy, State50("Live", 109_228.18)); + + // Before an engine moves it, the guard counts it for the demo account. + Assert.Equal(AccountStateFiles.LegacyPath(DataPath), AccountStateFiles.ReadablePathFor(DataPath, ExecutionMode.Demo, EnvironmentImport.ReadLegacyStateOwner(Root))); + Assert.Null(AccountStateFiles.ReadablePathFor(DataPath, ExecutionMode.Live, EnvironmentImport.ReadLegacyStateOwner(Root))); + + // The first 5.1 start (merged Demo) takes it as the demo account's own state. + BasketEngine demo = Engine(ExecutionMode.Demo); + demo.LoadState(); + demo.SaveState(); + await demo.DisposeAsync(); + Assert.Equal(109_228.18, Read(StateOf(ExecutionMode.Demo)).GetProperty("lastBalance").GetDouble(), 2); + Assert.False(File.Exists(StateOf(ExecutionMode.Live))); + Assert.True(File.Exists(Legacy + ".migrato")); + + // Weeks later, Live on a real account of 1 000 USD: nothing of the demo account comes with it. + JsonElement live = await StartLiveOnARealAccountOf1000(); + Assert.Equal(0, live.GetProperty("cumulativeCashFlow").GetDouble()); + Assert.Equal(1_000, live.GetProperty("peakNetEquity").GetDouble()); + Assert.DoesNotContain("movimento_di_cassa", LedgerText(), StringComparison.Ordinal); + } + + [Fact] + public async Task AFiftyFileWhoseAccountWasNotRecordedGoesAsideWhenItNamesAnotherMode() + { + // No record of the 5.0 configuration (no import, or an older marker): "Live" says nothing about the account. + WriteState(Legacy, State50("Live", 109_228.18)); + Assert.Null(AccountStateFiles.ReadablePathFor(DataPath, ExecutionMode.Demo)); + + BasketEngine demo = Engine(ExecutionMode.Demo); + demo.LoadState(); + demo.SaveState(); + await demo.DisposeAsync(); + + Assert.False(File.Exists(Legacy)); + Assert.True(File.Exists(Legacy + ".migrato")); + Assert.False(File.Exists(StateOf(ExecutionMode.Live)), "mai al conto reale senza sapere di chi era"); + Assert.Equal(0, Read(StateOf(ExecutionMode.Demo)).GetProperty("lastBalance").GetDouble()); + + JsonElement live = await StartLiveOnARealAccountOf1000(); + Assert.Equal(0, live.GetProperty("cumulativeCashFlow").GetDouble()); + Assert.DoesNotContain("movimento_di_cassa", LedgerText(), StringComparison.Ordinal); + } + + [Fact] + public async Task AFiftyPaperFileIsNeverResumedOnAnAccount() + { + DateTime opened = DateTime.UtcNow.AddHours(-5); + JsonObject Leg(string symbol, long id) => new() + { + ["symbol"] = symbol, ["instrumentId"] = 1, ["isBuy"] = true, ["units"] = 10_000, ["entryPrice"] = 1.1, ["positionId"] = id, + ["clientRef"] = "paper-" + id.ToString(CultureInfo.InvariantCulture), ["openedUtc"] = opened.ToString("O", CultureInfo.InvariantCulture), ["entryFeesUsd"] = 0, ["stopLossRate"] = 0, ["adds"] = new JsonArray(), + }; + JsonArray baskets = new(new JsonObject + { + ["name"] = "EURUSD/USDCHF", ["basketId"] = "B-paper", ["buyCross"] = true, ["openedUtc"] = opened.ToString("O", CultureInfo.InvariantCulture), + ["entryZ"] = -2.1, ["lastAddZ"] = -2.1, ["adds"] = 0, ["barsHeld"] = 3, ["entryCostPips"] = 1, ["tpPips"] = 20, ["maxLossUsd"] = 1_500, + ["equityAtEntry"] = 100_000, ["accruedFeesUsd"] = 0, ["entryMotivazione"] = "paper", ["a"] = Leg("EURUSD", 900_001), ["b"] = Leg("USDCHF", 900_002), + }); + Import50("Paper", "demo"); + WriteState(Legacy, State50("Paper", 100_000, baskets)); + Assert.Null(AccountStateFiles.ReadablePathFor(DataPath, ExecutionMode.Demo, EnvironmentImport.ReadLegacyStateOwner(Root))); + + // 5.1 reads the Paper configuration as Demo: the simulator's basket must not become a basket of the demo account. + AccountVenue demoAccount = new() { Balance = 50_000, Equity = 50_000 }; + BasketEngine engine = BasketEngine.OverVenue(Config(ExecutionMode.Demo), demoAccount); + await engine.LoadInstrumentsAsync(CancellationToken.None); + engine.LoadState(); + Assert.Equal(0, engine.CurrentActivity().OpenBaskets); + await engine.ReconcileAsync(CancellationToken.None); + Assert.Equal(0, engine.CurrentActivity().PendingSettlements); + await engine.DisposeAsync(); + + Assert.True(File.Exists(Legacy + ".migrato")); + Assert.False(File.Exists(StateOf(ExecutionMode.Live))); + } + + [Fact] + public async Task AFiftyDemoFileOfTheRealAccountGoesToTheRealAccount() + { + // 5.0's hole: Demo beside etoro.environment = real traded the REAL account (5.1 merges it to Demo). + Import50("Demo", "real"); + WriteState(Legacy, State50("Demo", 1_000)); + + BasketEngine demo = Engine(ExecutionMode.Demo); + demo.LoadState(); + demo.SaveState(); + await demo.DisposeAsync(); + + Assert.Equal(1_000, Read(StateOf(ExecutionMode.Live)).GetProperty("lastBalance").GetDouble()); + Assert.Equal(0, Read(StateOf(ExecutionMode.Demo)).GetProperty("lastBalance").GetDouble()); + Assert.True(File.Exists(Legacy + ".migrato")); + } + // ----------------------------------------------------------------------- // The guard on the engine's own slots // ----------------------------------------------------------------------- @@ -399,6 +557,58 @@ public sealed class AccountStateTests : TempFolderTests await idle.DisposeAsync(); } + /// + /// A leg of ours that no slot holds — leg A left on the account when its unwind close was refused, the slot in + /// Error without legs, the close order resolved Rejected — is not in the last reconciliation's picture for up to + /// twenty seconds: the guard reconciles first, so it counts as an orphan and the switch is refused (second review). + /// + [Fact] + public async Task TheGuardSeesALegNoSlotHoldsBeforeTheNextReconciliation() + { + Directory.CreateDirectory(StateDir); + DateTime sent = DateTime.UtcNow.AddSeconds(-30); + OrderTracker register = new(Path.Combine(StateDir, "pending_orders.json")); + TrackedOrder legA = register.Register(new TrackedOrder + { + ClientRef = "a-41", OrderId = 4101, Symbol = "EURUSD", InstrumentId = 1, IsBuy = true, RequestedUnits = 10_000, + Basket = "EURUSD/USDCHF", BasketId = "B41", Leg = OrderLeg.A, SentUtc = sent, Mode = "Demo", + }); + register.Apply(legA, new OrderOutcome(true, false, 4101, 41, 1.1, 10_000, sent.AddSeconds(1), 0, "Filled", string.Empty), sent.AddSeconds(1)); + + AccountVenue venue = new(); + venue.Positions.Add(new BrokerPosition(41, 1, true, 10_000, 1.1, sent.AddSeconds(1), 0, 0, 1, 1_100, 0, 0, 1.1)); + BasketEngine engine = BasketEngine.OverVenue(Config(ExecutionMode.Demo), venue); + engine.OrphanPolicy = OrphanPolicy.Report; + await engine.LoadInstrumentsAsync(CancellationToken.None); + engine.LoadState(); + Assert.False(engine.CurrentActivity().Busy, "l'ultima riconciliazione non l'ha ancora vista"); + + CommandResult check = await engine.RunCommandAsync(new EngineCommand(EngineCommandKind.PrepareAccountSwitch, "cambio di conto verso il reale", "prova"), CancellationToken.None); + + Assert.False(check.Ok, check.Message); + Assert.Equal(CommandResult.Refused, check.Code); + Assert.Equal(1, Assert.IsType(check.Payload).OrphanLegs); + await engine.DisposeAsync(); + } + + /// When the account's positions cannot be read, the guard cannot know what is on it: it refuses. + [Fact] + public async Task TheGuardRefusesWhenTheAccountsPositionsCannotBeRead() + { + AccountVenue venue = new() { PositionsFail = true }; + BasketEngine engine = BasketEngine.OverVenue(Config(ExecutionMode.Demo), venue); + await engine.LoadInstrumentsAsync(CancellationToken.None); + engine.LoadState(); + + CommandResult check = await engine.RunCommandAsync(new EngineCommand(EngineCommandKind.PrepareAccountSwitch, "cambio di conto verso il reale", "prova"), CancellationToken.None); + + Assert.False(check.Ok, check.Message); + Assert.Equal(CommandResult.Refused, check.Code); + Assert.True(Assert.IsType(check.Payload).AccountUnread); + Assert.Contains("posizioni del conto", check.Message, StringComparison.Ordinal); + await engine.DisposeAsync(); + } + // ----------------------------------------------------------------------- // The order register works on its own account // ----------------------------------------------------------------------- diff --git a/Encelado/tests/Encelado.Tests/CorrectionTests.cs b/Encelado/tests/Encelado.Tests/CorrectionTests.cs index 45647df..3961a73 100644 --- a/Encelado/tests/Encelado.Tests/CorrectionTests.cs +++ b/Encelado/tests/Encelado.Tests/CorrectionTests.cs @@ -342,7 +342,7 @@ public sealed class RealizedBackfillTests : TempFolderTests BackfillReport report = await Backfill(ledger).RunAsync(Now, CancellationToken.None); - Assert.Equal(new BackfillReport(5, 1, 3, 1), report); + Assert.Equal(new BackfillReport(5, 1, 3, 1) { CorrectedLegacy = 3 }, report); List rows = ledger.ReadBasketsCorrected(); BasketOutcomeRow b1 = rows.Single(static r => r.BasketId == CorrectionScenery.B1); Assert.Equal(-38.79, b1.PnlNetUsd, 2); @@ -380,6 +380,21 @@ public sealed class RealizedBackfillTests : TempFolderTests Assert.Equal(lines, ledger.ReadDecisionLines().Count); } + /// A row of 5.1 written with the estimate and corrected by the history is no wrong label of the old versions: it never re-masks nor replays the models (second review). + [Fact] + public async Task AnEstimateOf51CorrectedLaterIsNotALegacyLabel() + { + using Ledger ledger = new(LedgerDir); + ledger.Basket(CorrectionScenery.Row(CorrectionScenery.B1, "EURUSD/USDCAD", "tp_pips", -2.2, "2026-09-29T09:15:00Z", "2026-09-29T21:15:28.053Z", 5, "take-profit | P&L: stima dai prezzi di chiusura")); + ledger.Order(CorrectionScenery.Order("2026-09-29T09:15:58Z", CorrectionScenery.B1, "EURUSD/USDCAD", "EURUSD", true, OrderLeg.A, 3605914106, "a1")); + ledger.Order(CorrectionScenery.Order("2026-09-29T09:15:59Z", CorrectionScenery.B1, "EURUSD/USDCAD", "USDCAD", true, OrderLeg.B, 3605914105, "b1")); + + BackfillReport report = await Backfill(ledger).RunAsync(Now, CancellationToken.None); + + Assert.Equal(1, report.Corrected); + Assert.Equal(0, report.CorrectedLegacy); + } + [Fact] public void AnUnwoundAddIsNotAttributedToTheBasket() { diff --git a/Encelado/tests/Encelado.Tests/EnvironmentImportTests.cs b/Encelado/tests/Encelado.Tests/EnvironmentImportTests.cs index 75e9bee..4e54ea0 100644 --- a/Encelado/tests/Encelado.Tests/EnvironmentImportTests.cs +++ b/Encelado/tests/Encelado.Tests/EnvironmentImportTests.cs @@ -1,5 +1,6 @@ using System.Text.Json.Nodes; using Encelado.Core.Baskets; +using Encelado.Engine.Baskets; using Encelado.Engine.Configuration; namespace Encelado.Tests; @@ -286,4 +287,37 @@ public sealed class EnvironmentImportTests : IDisposable Assert.DoesNotContain("token-file", text, StringComparison.Ordinal); Assert.DoesNotContain("\"environment\"", text, StringComparison.Ordinal); } + + /// + /// 5.0's state file names the execution mode, not the account: the import records which account the 5.0 + /// configuration traded on (the variables winning over the file, as in 5.0), before a save can remove + /// etoro.environment from the file (second review). + /// + [Theory] + [InlineData("Live", "demo", "Live", ExecutionMode.Demo)] + [InlineData("Demo", "real", "Demo", ExecutionMode.Live)] + [InlineData("Live", "real", "Live", ExecutionMode.Live)] + [InlineData("LiveAuto", "demo", "Live", ExecutionMode.Demo)] + public void TheImportRecordsTheAccountThe50ConfigurationTradedOn(string mode, string environment, string label, ExecutionMode account) + { + ImportOutcome o = EnvironmentImport.Run(ConfigPath, Store(), Env(("ENCELADO_EXECUTION_MODE", mode), ("ETORO_ENVIRONMENT", environment)), Now); + + Assert.True(o.Ran); + Assert.Equal(new LegacyStateOwner(label, account), EnvironmentImport.ReadLegacyStateOwner(_dir)); + } + + [Fact] + public void APaperConfigurationRecordsNoAccountAndA51OneRecordsNothing() + { + ConfigWriter.Apply(ConfigPath, new Dictionary { ["run.executionMode"] = JsonValue.Create("Paper"), ["etoro.environment"] = JsonValue.Create("demo") }); + EnvironmentImport.Run(ConfigPath, Store(), Env(), Now); + Assert.Equal(new LegacyStateOwner("Paper", null), EnvironmentImport.ReadLegacyStateOwner(_dir)); + + // The factory file of 5.1 has no etoro.environment: it says nothing about 5.0. + System.IO.File.Delete(Marker); + System.IO.File.WriteAllText(ConfigPath, ConfigDefaults.Json); + EnvironmentImport.Run(ConfigPath, Store(), Env(), Now); + Assert.True(System.IO.File.Exists(Marker)); + Assert.Null(EnvironmentImport.ReadLegacyStateOwner(_dir)); + } } diff --git a/Encelado/tests/Encelado.Tests/LearningReviewTests.cs b/Encelado/tests/Encelado.Tests/LearningReviewTests.cs index ebf0053..54af243 100644 --- a/Encelado/tests/Encelado.Tests/LearningReviewTests.cs +++ b/Encelado/tests/Encelado.Tests/LearningReviewTests.cs @@ -444,6 +444,32 @@ public sealed class LearningReviewTests : TempFolderTests Assert.Equal(0, bad.Bandit.Arms.Sum(static a => a.N)); } + /// + /// A part never read well stays "never read well" at the next reading (second review): any other model file + /// rewritten moves the stamp, and the starting values shown then were called the last good reading. + /// + [Fact] + public void APartNeverReadWellIsNotCalledTheLastGoodReadingAtTheNextReading() + { + Directory.CreateDirectory(Models); + File.WriteAllText(Path.Combine(Models, "bandit.json"), "{ \"broken\": "); + File.WriteAllText(Path.Combine(Models, "last_cycle.json"), "{ \"broken\": "); + LearningLiveReport first = LearningDiskReader.ReadModels(Paths, ReviewScenery.Strategy(), CycleRunStatus.Idle, ReviewScenery.T0); + Assert.Contains("valori iniziali", Assert.Single(first.Warnings, static w => w.Contains("bandit.json non leggibile", StringComparison.Ordinal)), StringComparison.Ordinal); + Assert.Contains("non è mostrato", Assert.Single(first.Warnings, static w => w.Contains("last_cycle.json non leggibile", StringComparison.Ordinal)), StringComparison.Ordinal); + + // Another model file is written (an offline cycle, a hand edit): the models are read again. + File.WriteAllText(Path.Combine(Models, "learning_state.json"), LearningStateFile.Write(new LearningStateData { Version = 1 })); + LearningLiveReport second = LearningDiskReader.ReadModels(Paths, ReviewScenery.Strategy(), CycleRunStatus.Idle, ReviewScenery.T0.AddMinutes(1)); + + string bandit = Assert.Single(second.Warnings, static w => w.Contains("bandit.json non leggibile", StringComparison.Ordinal)); + Assert.DoesNotContain("ultima lettura buona", bandit, StringComparison.Ordinal); + Assert.Contains("valori iniziali", bandit, StringComparison.Ordinal); + string cycle = Assert.Single(second.Warnings, static w => w.Contains("last_cycle.json non leggibile", StringComparison.Ordinal)); + Assert.DoesNotContain("ultima lettura buona", cycle, StringComparison.Ordinal); + Assert.Equal(1, second.Status.ModelVersion); + } + [Fact] public void AFileThatIsGoneIsNotKeptAsTheLastGoodReading() { @@ -715,4 +741,76 @@ public sealed class LearningReviewTests : TempFolderTests Assert.Single(Directory.GetDirectories(Path.Combine(models, "ritirati"))); await next.DisposeAsync(); } + + private BotConfig LiveConfig() + { + BotConfig c = Config(); + c.Run.ExecutionMode = "Live"; + c.Run.AllowLive = true; + return c; + } + + /// + /// Rows of 4.0–5.0 on both accounts (second review). The first start, on Demo, corrects the demo's row and + /// retires the models; the real account's row keeps the proceeds label — a win — until a Live start corrects + /// it. Every evaluation row of the Demo session carried a lastNOutcomes computed with that wrong label, and the + /// logistic learnt it: the Live start that corrects it masks the feature again up to now and replays the + /// logistic on the corrected labels, leaving the bandit and the retire mark alone. + /// + [Fact] + public async Task TheSecondAccountsCorrectionsMaskTheFeatureAgainAndReplayTheLogistic() + { + string ledgerDir = Path.Combine(DataPath, "ledger"); + using (Ledger ledger = new(ledgerDir)) + { + ledger.Basket(CorrectionScenery.Row("BD", ReviewScenery.Pair, "tp_pips", -2.2, "2026-09-29T10:00:00Z", "2026-09-29T20:00:00Z", 15_000)); + ledger.Basket(CorrectionScenery.Row("BL", ReviewScenery.Pair, "tp_pips", -2.2, "2026-09-28T10:00:00Z", "2026-09-28T20:00:00Z", 15_000, mode: "Live")); + ledger.Order(CorrectionScenery.Order("2026-09-29T10:00:01Z", "BD", ReviewScenery.Pair, "EURUSD", true, OrderLeg.A, 7001, "aBD")); + ledger.Order(CorrectionScenery.Order("2026-09-29T10:00:02Z", "BD", ReviewScenery.Pair, "USDCHF", true, OrderLeg.B, 7002, "bBD")); + ledger.Order(CorrectionScenery.Order("2026-09-28T10:00:01Z", "BL", ReviewScenery.Pair, "EURUSD", true, OrderLeg.A, 7101, "aBL")); + ledger.Order(CorrectionScenery.Order("2026-09-28T10:00:02Z", "BL", ReviewScenery.Pair, "USDCHF", true, OrderLeg.B, 7102, "bBL")); + CorrectionScenery.Ingresso(ledger, "BD", new DateTime(2026, 9, 29, 10, 0, 0, DateTimeKind.Utc)); + CorrectionScenery.Ingresso(ledger, "BL", new DateTime(2026, 9, 28, 10, 0, 0, DateTimeKind.Utc)); + } + + string feature = LearningFeatures.Names[LearningFeatures.LastOutcomesIndex]; + + // The first 5.1 start, on Demo: its history knows only the demo positions. + MoneyVenue demo = new(); + demo.History.Add(DemoHistory.Trade(7001, 1, true, 10_000, 1.1, 1.1, "2026-09-29T10:00:01Z", "2026-09-29T20:00:00Z", -10)); + demo.History.Add(DemoHistory.Trade(7002, 6, true, 10_000, 0.9, 0.9, "2026-09-29T10:00:02Z", "2026-09-29T20:00:00Z", -20)); + BasketEngine d = BasketEngine.OverVenue(Config(), demo); + LearningState dl = d.StartLearning(); + await d.LoadInstrumentsAsync(CancellationToken.None); + d.LoadState(); + await d.BackfillRealizedAsync(CancellationToken.None); + Assert.True(dl.LabelsFixed); + Assert.Equal(0.5, dl.LastOutcomes, 9); // BL is still the proceeds' "win" in the Demo session + DateTime maskAfterDemo = Ledger.ReadFeatureMaskUntil(ledgerDir, feature); + double[] entry = dl.BuildDataset().First().Features; + string bandit = dl.BanditJson; + await d.DisposeAsync(); + + // The first Live start corrects BL. + MoneyVenue live = new(); + live.History.Add(DemoHistory.Trade(7101, 1, true, 10_000, 1.1, 1.1, "2026-09-28T10:00:01Z", "2026-09-28T20:00:00Z", -15)); + live.History.Add(DemoHistory.Trade(7102, 6, true, 10_000, 0.9, 0.9, "2026-09-28T10:00:02Z", "2026-09-28T20:00:00Z", -15)); + BasketEngine l = BasketEngine.OverVenue(LiveConfig(), live, startConfirmed: true); + LearningState ll = l.StartLearning(); + await l.LoadInstrumentsAsync(CancellationToken.None); + l.LoadState(); + double before = ll.Predict(entry); + await l.BackfillRealizedAsync(CancellationToken.None); + + Assert.Equal(0, ll.LastOutcomes, 9); + Assert.True(Ledger.ReadFeatureMaskUntil(ledgerDir, feature) > maskAfterDemo, "le righe della sessione Demo hanno lastNOutcomes calcolata con l'etichetta sbagliata"); + Assert.True(ll.Predict(entry) < before, "la logistica ha rifatto BL con l'etichetta corretta"); + Assert.Equal(2, ll.LogisticSeen); + Assert.True(ll.LabelsFixed); + Assert.Equal(bandit, ll.BanditJson); + await l.DisposeAsync(); + + using Ledger read = new(ledgerDir); + Assert.All(read.ReadBasketsCorrected(), static r => Assert.Equal(0, r.Label)); + } } diff --git a/Encelado/tests/Encelado.Tests/LifecycleTests.cs b/Encelado/tests/Encelado.Tests/LifecycleTests.cs index 6311ba1..70af251 100644 --- a/Encelado/tests/Encelado.Tests/LifecycleTests.cs +++ b/Encelado/tests/Encelado.Tests/LifecycleTests.cs @@ -82,6 +82,9 @@ internal sealed class GatedEngine(int id, string? lockPath = null) : IEngine /// The engine's own flag (): false while it would still be warming up. public bool LoopStarted { get; set; } = true; + /// The critical command the engine has in hand, whoever still waits for its answer (set by the test, as a real engine would). + public string? CriticalCommand { get; set; } + public Task ExecuteAsync(EngineCommand command, CancellationToken ct) { lock (_commands) @@ -303,6 +306,92 @@ public sealed class LifecycleTests : TempFolderTests Assert.Null(supervisor.CommandInProgress); } + /// + /// A kill-switch holds FERMA and the restarts back while the engine has it, not while its caller waits + /// (second review): a tab closed or reloaded during the kill, a Telegram poller stopped in the middle of + /// /kill, or the 120 s wait over, used to free FERMA while the decision thread was still closing. + /// + [Fact] + public async Task AKillWhoseCallerStoppedWaitingStillHoldsBackFermaUntilTheEngineIsDoneWithIt() + { + BotConfig config = Config(); + TaskCompletionSource killing = new(TaskCreationOptions.RunContinuationsAsynchronously); + GatedEngine engine = new(1); + + // As BasketEngine does: the decision thread keeps the kill whatever its caller does; only the wait observes the token. + engine.Answer = (c, ct) => + { + if (c.Kind != EngineCommandKind.KillSwitch) + { + return Task.FromResult(new CommandResult(true, "ok")); + } + + engine.CriticalCommand = "kill-switch"; + _ = killing.Task.ContinueWith(_ => engine.CriticalCommand = null, TaskScheduler.Default); + return killing.Task.WaitAsync(ct); + }; + await using BotSupervisor supervisor = new(config, (_, _) => engine); + Assert.True((await supervisor.StartAsync()).Ok); + + using CancellationTokenSource request = new(); + Task kill = supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.KillSwitch, string.Empty, "kill-switch dalla web UI"), request.Token); + await request.CancelAsync(); + await Assert.ThrowsAnyAsync(() => kill); + + Assert.Equal("kill-switch", supervisor.CommandInProgress); + CommandResult ferma = await supervisor.StopAsync(); + Assert.False(ferma.Ok, ferma.Message); + Assert.Equal(CommandResult.Refused, ferma.Code); + RestartResult restart = await supervisor.RestartAsync("prova", liveConfirmed: false); + Assert.False(restart.Stopped); + Assert.Equal(CommandResult.Refused, restart.Result.Code); + Assert.False(engine.Disposed); + + // The engine is done with it: FERMA goes through. + killing.SetResult(new CommandResult(true, "kill-switch eseguito")); + using CancellationTokenSource wait = new(Wait); + while (supervisor.CommandInProgress is not null) + { + await Task.Delay(10, wait.Token); + } + + Assert.True((await supervisor.StopAsync()).Ok); + } + + /// The real engine counts a critical command from the queue to the end of its run on the decision thread, or until the run ends without it. + [Fact] + public async Task TheEngineCountsACriticalCommandUntilItsDecisionThreadIsDoneWithIt() + { + BotConfig config = Config(); + BasketEngine engine = new(config, null, false); + using CancellationTokenSource request = new(); + Task kill = engine.ExecuteAsync(new EngineCommand(EngineCommandKind.KillSwitch, string.Empty, "prova"), request.Token); + Task pause = engine.ExecuteAsync(new EngineCommand(EngineCommandKind.Pause, string.Empty, "prova"), CancellationToken.None); + await request.CancelAsync(); + await Assert.ThrowsAnyAsync(() => kill); + + Assert.Equal("kill-switch", engine.CriticalCommand); + + // Without keys the start fails before the loop: the queue is answered, and nothing is in hand any more. + await Assert.ThrowsAsync(() => engine.RunAsync(CancellationToken.None)); + Assert.False((await pause.WaitAsync(Wait)).Ok); + Assert.Null(engine.CriticalCommand); + await engine.DisposeAsync(); + + // A running engine: the close stays counted after its caller left, until the decision thread has run it. + BasketEngine running = BasketEngine.OverVenue(config, new AccountVenue()); + await running.LoadInstrumentsAsync(CancellationToken.None); + running.LoadState(); + using CancellationTokenSource tab = new(); + Task close = running.ExecuteAsync(new EngineCommand(EngineCommandKind.Close, "EURUSD/USDCHF", "prova"), tab.Token); + await tab.CancelAsync(); + await Assert.ThrowsAnyAsync(() => close); + Assert.Equal("chiusura di EURUSD/USDCHF", running.CriticalCommand); + await running.DrainCommandsAsync(CancellationToken.None); + Assert.Null(running.CriticalCommand); + await running.DisposeAsync(); + } + [Fact] public async Task EseguiCicloIsRefusedUntilTheDecisionLoopRuns() { diff --git a/Encelado/tests/Encelado.Tests/MoneyRiskTests.cs b/Encelado/tests/Encelado.Tests/MoneyRiskTests.cs index 1913093..9b247a0 100644 --- a/Encelado/tests/Encelado.Tests/MoneyRiskTests.cs +++ b/Encelado/tests/Encelado.Tests/MoneyRiskTests.cs @@ -359,6 +359,82 @@ public sealed class MoneyRiskTests : TempFolderTests await engine.DisposeAsync(); } + private static BrokerPosition Held(long id, long instrument, double unrealized) => + new(id, instrument, true, 100_000, 1.1, Opened, 0, 0, 10, 11_000, unrealized, 0, 1.1); + + /// + /// A close at −3 500 pushes the day past the threshold while the venue's history does not list it yet; the + /// equity then recovers to −2.9 % before the history explains the fall (second review). Entries stay suspended + /// for the whole window, and the explaining reading latches the day when the fall was a trading loss — as the + /// backtest on the same path does — and lifts the suspension when it was cash taken out. + /// + [Theory] + [InlineData(-3_500, true)] + [InlineData(0, false)] + public async Task AFallExplainedAfterTheEquityRecoveredLatchesTheDayOnlyWhenItWasALoss(double closedPnl, bool latched) + { + WriteState(State(100_000, 31, 32)); + MoneyVenue venue = new() { Balance = 100_000, Equity = 97_100 }; + venue.Positions[31] = Held(31, 1, -2_900); + venue.Positions[32] = Held(32, 2, 0); + BasketEngine engine = await StartAsync(venue); + await engine.ReconcileAsync(Ct); + Assert.False((await engine.ContextAsync(Pair, Ct)).DailyLossHit); + + // Position 31 closes at −3 500; the history lags. + venue.Positions.Remove(31); + venue.Balance = 96_500; + venue.Equity = 96_500; + await engine.ReconcileAsync(Ct); + Assert.True((await engine.ContextAsync(Pair, Ct)).DailyLossHit); + + // Position 32 gains 600 while the history still does not list 31: still suspended. + venue.Positions[32] = Held(32, 2, 600); + venue.Equity = 97_100; + await engine.ReconcileAsync(Ct); + Assert.True((await engine.ContextAsync(Pair, Ct)).DailyLossHit, "finché il calo non è spiegato le entrate restano sospese"); + engine.PublishView(); + Assert.False(engine.View!.Funds.DailyLossLatched); + Assert.True(engine.View.Funds.DailyLossHit, "la pagina dice che le entrate sono sospese"); + + // The history explains the fall: a trading loss latches the day, a withdrawal lifts the suspension. + venue.History.Add(Trade(31, 1, closedPnl)); + engine.ForgetHistoryReading(); + await engine.ReconcileAsync(Ct); + Assert.Equal(latched, (await engine.ContextAsync(Pair, Ct)).DailyLossHit); + engine.PublishView(); + Assert.Equal(latched, engine.View!.Funds.DailyLossLatched); + await engine.DisposeAsync(); + } + + /// A deposit that arrives while a small fall is unexplained is never read as a loss of the window: the day is not latched. + [Fact] + public async Task ADepositWhileAFallIsUnexplainedNeverLatchesTheDay() + { + WriteState(State(100_000, 31)); + MoneyVenue venue = new(); + venue.Positions[31] = Held(31, 1, 0); + BasketEngine engine = await StartAsync(venue); + + venue.Positions.Remove(31); + venue.Balance = 99_000; + venue.Equity = 99_000; + await engine.ReconcileAsync(Ct); + + venue.Balance = 109_000; + venue.Equity = 109_000; + await engine.ReconcileAsync(Ct); + + venue.History.Add(Trade(31, 1, -1_000)); + engine.ForgetHistoryReading(); + await engine.ReconcileAsync(Ct); + Assert.False((await engine.ContextAsync(Pair, Ct)).DailyLossHit); + engine.PublishView(); + Assert.False(engine.View!.Funds.DailyLossLatched); + Assert.Equal(10_000, engine.View.Funds.CumulativeCashFlow, 2); + await engine.DisposeAsync(); + } + // ----------------------------------------------------------------------- // soldi-rischio-05 — a position already recorded is never recorded again // ----------------------------------------------------------------------- @@ -675,7 +751,7 @@ public sealed class MoneyRiskTests : TempFolderTests } [Fact] - public void AnEntryKeepsItsPresetFromThePlanToThePositionAndThroughARestart() + public void APendingEntryKeepsItsPresetInTheSavedPlan() { PendingEntry plan = new() { @@ -694,6 +770,97 @@ public sealed class MoneyRiskTests : TempFolderTests Assert.Equal("CONSERVATIVE", PendingEntry.Read(doc.RootElement.GetProperty("pending")).Preset); } + /// A venue that fills every order at once (the executor's entry, end to end). + private sealed class FillingVenue : IBroker + { + private long _next = 1; + + public BrokerEnvironment Environment => BrokerEnvironment.Backtest; + + public string Name => "riempie tutto"; + + public bool SupportsTrading => true; + + public TimeSpan ClockSkew => TimeSpan.Zero; + + public Task> GetInstrumentsAsync(IReadOnlyList symbols, CancellationToken ct) => Task.FromResult>([]); + + public Task> GetQuotesAsync(IReadOnlyList instrumentIds, CancellationToken ct) => Task.FromResult>([]); + + public Task> GetCandlesAsync(long instrumentId, TimeSpan interval, int count, CancellationToken ct) => Task.FromResult>([]); + + public Task GetAccountAsync(CancellationToken ct) => Task.FromResult(new AccountSnapshot(DateTime.UtcNow, "USD", 100_000, 100_000, 100_000, 0, 0)); + + public Task> GetPositionsAsync(CancellationToken ct) => Task.FromResult>([]); + + public Task OpenAsync(OrderRequest request, CancellationToken ct) + { + long id = _next++; + return Task.FromResult(new OrderOutcome(true, false, id, id, request.IsBuy ? 1.1001 : 1.0999, request.Units, DateTime.UtcNow, 0, "Filled", string.Empty)); + } + + public Task LookupOrderAsync(string clientRef, CancellationToken ct) => Task.FromResult(null); + + public Task LookupOrderByIdAsync(long orderId, CancellationToken ct) => Task.FromResult(null); + + public Task CancelOrderAsync(long orderId, CancellationToken ct) => Task.FromResult(false); + + public Task CloseAsync(long positionId, long instrumentId, CancellationToken ct) => throw new NotSupportedException("nessuna chiusura in questo test"); + + public Task UpdateStopsAsync(long positionId, double? stopLoss, double? takeProfit, CancellationToken ct) => Task.FromResult(true); + + public Task GetCostAsync(OrderRequest request, CancellationToken ct) => Task.FromResult(null); + + public Task> GetClosedTradesAsync(DateTime fromUtc, CancellationToken ct) => Task.FromResult>([]); + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + + /// + /// The preset of the decision reaches the position the executor builds — the one the basket's row and the + /// bandit's reward will name — whatever the strategy says (second review: removing it failed no test). + /// + [Fact] + public async Task TheExecutorGivesThePositionThePresetOfTheDecision() + { + BasketStrategyConfig cfg = BasketStrategyConfig.ParseText(BasketStrategyConfig.DefaultJson, out _); + Assert.NotEqual(PresetName.Conservative, cfg.Preset); + Instrument eurusd = new(1, "EURUSD", "EUR/USD", "Forex", 0.0001, 5, 0.01, 2_000_000, 1000, [1, 2, 5, 10], true, true, 0, 50, string.Empty); + Instrument usdchf = new(6, "USDCHF", "USD/CHF", "Forex", 0.0001, 5, 0.01, 2_000_000, 1000, [1, 2, 5, 10], true, true, 0, 50, string.Empty); + SymbolSeries a = new(eurusd, TimeSpan.FromMinutes(15)); + SymbolSeries b = new(usdchf, TimeSpan.FromMinutes(15)); + DateTime now = new(2026, 9, 16, 10, 0, 0, DateTimeKind.Utc); + a.OnQuote(new QuoteSnapshot(1, now, 1.1000, 1.1001, true), now); + b.OnQuote(new QuoteSnapshot(6, now, 0.9000, 0.9001, true), now); + static double? Mid(string s) => s == "EURUSD" ? 1.10005 : s == "USDCHF" ? 0.90005 : null; + BasketContext ctx = new() + { + TimeUtc = now, BasketId = Pair, Name = Pair, Cross = SyntheticCross.Derive("EURUSD", "USDCHF"), A = a, B = b, Equity = 10_000, + PipValueUsdA = 0.0001, PipValueUsdB = 0.0001 / 0.9, UsdPerQuoteA = 1, UsdPerQuoteB = 1 / 0.9, Mid = Mid, + }; + BasketDecision d = new(DecisionKind.Enter, true, new SizingResult(true, 10_000, 9_000, 11_000, 10_000, 50, 2.1, "prova"), ["enter"], "prova", new BasketEvaluation { Z = -2.2 }, null); + + EntryOutcome outcome = await new BasketExecutor(new FillingVenue(), cfg, Mid, static _ => { }).OpenAsync(ctx, d, cfg.Effective(PresetName.Conservative), "B1", Ct); + + Assert.True(outcome.Ok, outcome.Error); + Assert.Equal("CONSERVATIVE", outcome.Position!.Preset); + } + + /// A basket entered with MODERATE keeps it in the state the engine saves, with AGGRESSIVE in force: a restart rewards MODERATE. + [Fact] + public async Task TheSavedStateKeepsThePresetABasketEnteredWith() + { + WriteStrategy(static s => s["preset"] = "Aggressive"); + JsonObject state = State(); + state["baskets"] = new JsonArray(OpenBasket("MODERATE")); + WriteState(state); + BasketEngine engine = await StartAsync(new MoneyVenue(), judgeTheBalance: false); + engine.SaveState(); + await engine.DisposeAsync(); + + Assert.Equal("MODERATE", Read(StatePath).GetProperty("baskets")[0].GetProperty("preset").GetString()); + } + // ----------------------------------------------------------------------- // interfaccia-api-kill-foreign-override — the operator's choice wins over the setting // ----------------------------------------------------------------------- diff --git a/Encelado/tests/Encelado.Tests/SettingsRuntimeTests.cs b/Encelado/tests/Encelado.Tests/SettingsRuntimeTests.cs index 6ac1a82..2c4d2d4 100644 --- a/Encelado/tests/Encelado.Tests/SettingsRuntimeTests.cs +++ b/Encelado/tests/Encelado.Tests/SettingsRuntimeTests.cs @@ -297,6 +297,49 @@ public sealed class SettingsRuntimeTests : IAsyncLifetime Assert.Equal(BotState.Stopped, Supervisor.State); } + /// + /// Another tab switched the account to Live (with the phrase) while eToro checked a pair of demo keys: they are no + /// longer the running engine's, and the save restarts nothing (second review: it stopped the Live engine and left it + /// stopped, the phrase missing, with the real account's baskets under the native stops only). + /// + [Fact] + public async Task KeysOfTheAccountLeftWhileTheyWereCheckedRestartNothing() + { + Build(static p => Set(p, "run.allowLive", true)); + Assert.True((await Runtime.StartEngineAsync(null)).Ok); + SettingsResult? switched = null; + _duringKeyCheck = async () => switched ??= await Runtime.ApplyAsync(new Dictionary { ["run.executionMode"] = "Live" }, LiveConfirmation.Phrase, CancellationToken.None); + + SecretActionResult keys = await Runtime.SaveKeysAsync("demo", "api-demo-2", "user-demo-2", null, CancellationToken.None); + + Assert.NotNull(switched); + Assert.True(switched.Ok, switched.Message); + Assert.True(keys.Ok, keys.Message); + Assert.Equal(SettingsResult.RestartNone, keys.Restart); + Assert.Equal("api-demo-2", Runtime.Secrets.Etoro(demo: true)!.ApiKey); + Assert.Equal(2, _engines.Count); + Assert.Equal(ExecutionMode.Live, _engines[1].Mode); + Assert.Equal(BotState.Running, Supervisor.State); + } + + /// Real keys that became the running engine's while they were checked (the account went Live meanwhile): saved, and a Live restart still needs the phrase. + [Fact] + public async Task KeysThatBecameTheLiveEnginesWhileCheckedAreSavedWithoutARestart() + { + Build(static p => Set(p, "run.allowLive", true)); + Assert.True((await Runtime.StartEngineAsync(null)).Ok); + _duringKeyCheck = async () => Assert.True((await Runtime.ApplyAsync(new Dictionary { ["run.executionMode"] = "Live" }, LiveConfirmation.Phrase, CancellationToken.None)).Ok); + + SecretActionResult keys = await Runtime.SaveKeysAsync("live", "api-real-2", "user-real-2", null, CancellationToken.None); + + Assert.True(keys.Ok, keys.Message); + Assert.Equal(SettingsResult.RestartNone, keys.Restart); + Assert.Contains(LiveConfirmation.Phrase, keys.Message, StringComparison.Ordinal); + Assert.Equal("api-real-2", Runtime.Secrets.Etoro(demo: false)!.ApiKey); + Assert.Equal(2, _engines.Count); + Assert.Equal(BotState.Running, Supervisor.State); + } + [Fact] public async Task AKillSwitchInProgressIsNeverCutByASaveOrByFerma() { diff --git a/Encelado/tests/Encelado.Tests/WebTests.cs b/Encelado/tests/Encelado.Tests/WebTests.cs index 73a4402..fc5f2db 100644 --- a/Encelado/tests/Encelado.Tests/WebTests.cs +++ b/Encelado/tests/Encelado.Tests/WebTests.cs @@ -440,9 +440,20 @@ public sealed class WebHostTests : IAsyncLifetime Assert.False(WebHost.IsPublic("/api/settings")); } + /// The server's own secret of this folder (created by the host at its start). + private byte[] SessionSecret() => File.ReadAllBytes(Path.Combine(_dir, SessionKey.FileName)); + + /// A request carrying a session cookie. + private static HttpRequestMessage WithCookie(string path, string value) + { + HttpRequestMessage req = new(HttpMethod.Get, path); + req.Headers.Add("Cookie", $"{WebHost.CookieName}={value}"); + return req; + } + /// /// The password is asked once (field password, the 5.0 field token still - /// accepted); the browser then carries an HMAC derived from it, never the password. + /// accepted); the browser then carries an HMAC of it and of the server's own secret, never the password. /// [Fact] public async Task TheLoginSetsASessionCookieThatIsNotThePassword() @@ -455,21 +466,23 @@ public sealed class WebHostTests : IAsyncLifetime Assert.Contains("httponly", cookie, StringComparison.OrdinalIgnoreCase); Assert.Contains("samesite=strict", cookie, StringComparison.OrdinalIgnoreCase); string value = cookie[(WebHost.CookieName.Length + 1)..].Split(';')[0]; - Assert.Equal(WebHost.SessionValue(Password), value); + Assert.Equal(WebHost.SessionValue(SessionSecret(), Password), value); Assert.DoesNotContain(Password, cookie, StringComparison.Ordinal); - Assert.NotEqual(WebHost.SessionValue("un'altra password"), value); + Assert.NotEqual(WebHost.SessionValue(SessionSecret(), "un'altra password"), value); - HttpRequestMessage withCookie = new(HttpMethod.Get, "/api/snapshot"); - withCookie.Headers.Add("Cookie", $"{WebHost.CookieName}={value}"); - Assert.Equal(HttpStatusCode.OK, (await _client.SendAsync(withCookie)).StatusCode); + // The secret is the server's own: from the password alone the cookie cannot be computed. + Assert.Equal(SessionKey.Size, SessionSecret().Length); + Assert.NotEqual(WebHost.SessionValue(new byte[SessionKey.Size], Password), value); + + Assert.Equal(HttpStatusCode.OK, (await _client.SendAsync(WithCookie("/api/snapshot", value))).StatusCode); using FormUrlEncodedContent legacy = new([new KeyValuePair("token", Password)]); Assert.Equal(HttpStatusCode.Redirect, (await _client.PostAsync("/login", legacy)).StatusCode); - // Last: a wrong cookie is a wrong password, and the address then waits (see the backoff's test). - HttpRequestMessage rawPassword = new(HttpMethod.Get, "/api/snapshot"); - rawPassword.Headers.Add("Cookie", $"{WebHost.CookieName}={Password}"); - Assert.Equal(HttpStatusCode.Unauthorized, (await _client.SendAsync(rawPassword)).StatusCode); + // A wrong cookie is simply not signed in, at once: it is no password guess. + System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew(); + Assert.Equal(HttpStatusCode.Unauthorized, (await _client.SendAsync(WithCookie("/api/snapshot", Password))).StatusCode); + Assert.True(sw.Elapsed < TimeSpan.FromMilliseconds(800), $"risposta in {sw.Elapsed.TotalMilliseconds:F0} ms"); HttpResponseMessage logout = await _client.PostAsync("/logout", null); Assert.Equal(HttpStatusCode.Redirect, logout.StatusCode); @@ -498,14 +511,14 @@ public sealed class WebHostTests : IAsyncLifetime } /// - /// A wrong Bearer or session cookie is a guess of the password like a wrong login (the cookie is derived - /// from it, so it can be computed for every guess): one address gets one password checked at a time, the - /// wrong one answered only when its wait ends — 1 s, then 2, 4… up to 30 s in a row — and meanwhile no - /// password of that address is even checked, a right one included: parallel guesses do not help (5.1 - /// review: 200 wrong Bearers took 53 ms, 40 parallel logins one second). + /// A wrong Bearer is a guess of the password like a wrong login: one address gets one password checked at a + /// time, the wrong one answered only when its wait ends — 1 s, then 2, 4… up to 30 s in a row — and meanwhile + /// no password of that address is even checked, a right one included: parallel guesses do not help (5.1 + /// review: 200 wrong Bearers took 53 ms, 40 parallel logins one second). A signed-in page of the same address + /// is not kept out meanwhile (second review). /// [Fact] - public async Task AWrongBearerOrCookieIsAGuessAndTheAddressWaitsBeforeTheNext() + public async Task AWrongBearerIsAGuessAndTheAddressWaitsBeforeTheNext() { System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew(); HttpResponseMessage[] guesses = await Task.WhenAll(Enumerable.Range(0, 12).Select(i => @@ -526,12 +539,13 @@ public sealed class WebHostTests : IAsyncLifetime Assert.Contains("riprova", body.RootElement.GetProperty("message").GetString(), StringComparison.Ordinal); } - // The second guess in a row, a wrong session cookie: its answer comes after two seconds, and while it - // waits even the right password from the same address is not checked. - HttpRequestMessage cookie = new(HttpMethod.Get, "/api/snapshot"); - cookie.Headers.Add("Cookie", $"{WebHost.CookieName}={WebHost.SessionValue("una-password-sbagliata")}"); + // The second guess in a row: its answer comes after two seconds, and while it waits even the right password + // from the same address is not checked — but a page already signed in there goes on, and a stale cookie is + // simply not signed in. + HttpRequestMessage guess = new(HttpMethod.Get, "/api/snapshot"); + guess.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "una-password-sbagliata"); sw.Restart(); - Task second = _client!.SendAsync(cookie); + Task second = _client!.SendAsync(guess); await Task.Delay(300); HttpResponseMessage right = await _client.SendAsync(Authorised(HttpMethod.Get, "/api/settings")); Assert.Equal(HttpStatusCode.TooManyRequests, right.StatusCode); @@ -540,6 +554,8 @@ public sealed class WebHostTests : IAsyncLifetime Assert.Equal(HttpStatusCode.TooManyRequests, login.StatusCode); Assert.Contains("login-error", await login.Content.ReadAsStringAsync(), StringComparison.Ordinal); Assert.False(login.Headers.Contains("Set-Cookie")); + Assert.Equal(HttpStatusCode.OK, (await _client.SendAsync(WithCookie("/api/snapshot", WebHost.SessionValue(SessionSecret(), Password)))).StatusCode); + Assert.Equal(HttpStatusCode.Unauthorized, (await _client.SendAsync(WithCookie("/api/snapshot", WebHost.SessionValue(SessionSecret(), "una-vecchia-password")))).StatusCode); Assert.Equal(HttpStatusCode.Unauthorized, (await second).StatusCode); Assert.True(sw.Elapsed >= TimeSpan.FromMilliseconds(1_900), $"risposta in {sw.Elapsed.TotalMilliseconds:F0} ms"); @@ -552,6 +568,51 @@ public sealed class WebHostTests : IAsyncLifetime Assert.InRange(sw.Elapsed, TimeSpan.FromMilliseconds(900), TimeSpan.FromMilliseconds(1_900)); } + /// + /// A tab left open over a password change keeps sending its old cookie, about once a second (second review): + /// each request is simply not signed in, at once, and the right password typed meanwhile on the same computer + /// opens at the first try — it used to get 429 for as long as the old tab stayed open. + /// + [Fact] + public async Task AStaleTabNeverKeepsTheRightPasswordOut() + { + string stale = WebHost.SessionValue(SessionSecret(), "la-password-di-prima"); + System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew(); + for (int i = 0; i < 5; i++) + { + HttpResponseMessage r = await _client!.SendAsync(WithCookie("/api/snapshot", stale)); + Assert.Equal(HttpStatusCode.Unauthorized, r.StatusCode); + Assert.False(r.Headers.Contains("Retry-After")); + } + + Assert.True(sw.Elapsed < TimeSpan.FromSeconds(2), $"cinque richieste in {sw.Elapsed.TotalMilliseconds:F0} ms"); + HttpResponseMessage page = await _client!.SendAsync(WithCookie("/", stale)); + Assert.Equal(HttpStatusCode.Redirect, page.StatusCode); + Assert.Equal("/login", page.Headers.Location?.ToString()); + + using FormUrlEncodedContent form = new([new KeyValuePair("password", Password)]); + HttpResponseMessage login = await _client.PostAsync("/login", form); + Assert.Equal(HttpStatusCode.Redirect, login.StatusCode); + Assert.True(login.Headers.Contains("Set-Cookie")); + } + + /// The operator's signed-in page never clears a guesser's count on the same address: the next wrong Bearer waits two seconds, not one. + [Fact] + public async Task ASignedInPageDoesNotResetAGuessersWait() + { + HttpRequestMessage first = new(HttpMethod.Get, "/api/snapshot"); + first.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "primo-tentativo"); + Assert.Equal(HttpStatusCode.Unauthorized, (await _client!.SendAsync(first)).StatusCode); + + Assert.Equal(HttpStatusCode.OK, (await _client.SendAsync(WithCookie("/api/snapshot", WebHost.SessionValue(SessionSecret(), Password)))).StatusCode); + + HttpRequestMessage next = new(HttpMethod.Get, "/api/snapshot"); + next.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "secondo-tentativo"); + System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew(); + Assert.Equal(HttpStatusCode.Unauthorized, (await _client.SendAsync(next)).StatusCode); + Assert.True(sw.Elapsed >= TimeSpan.FromMilliseconds(1_900), $"risposta in {sw.Elapsed.TotalMilliseconds:F0} ms"); + } + /// /// What another site's page can send without a preflight (a form, a no-cors fetch with text/plain) never /// changes anything: under /api/ a write must say application/json (415 otherwise, bodyless @@ -895,6 +956,40 @@ public sealed class AuthBackoffTests } } +/// The server's own secret in the session cookie (second review): created once, kept across restarts, its own per folder. +public sealed class SessionKeyTests : TempFolderTests +{ + [Fact] + public void TheKeyIsCreatedOnceAndKeptAcrossRestarts() + { + byte[] first = SessionKey.LoadOrCreate(Root, out string? problem); + Assert.Null(problem); + Assert.Equal(SessionKey.Size, first.Length); + Assert.Equal(first, File.ReadAllBytes(Path.Combine(Root, SessionKey.FileName))); + + // A restart reads the same key: the sessions survive it. + Assert.Equal(first, SessionKey.LoadOrCreate(Root, out _)); + Assert.Equal(WebHost.SessionValue(first, "password"), WebHost.SessionValue(SessionKey.LoadOrCreate(Root, out _), "password")); + + // Another folder, another key: a cookie of one server opens nothing on another. + string other = Path.Combine(Root, "altro"); + Assert.NotEqual(WebHost.SessionValue(first, "password"), WebHost.SessionValue(SessionKey.LoadOrCreate(other, out _), "password")); + } + + [Fact] + public void ADamagedKeyIsReplacedAndSaysSo() + { + File.WriteAllText(Path.Combine(Root, SessionKey.FileName), "corto"); + + byte[] key = SessionKey.LoadOrCreate(Root, out string? problem); + + Assert.Equal(SessionKey.Size, key.Length); + Assert.NotNull(problem); + Assert.Contains("nuovo accesso", problem, StringComparison.Ordinal); + Assert.Equal(key, SessionKey.LoadOrCreate(Root, out _)); + } +} + /// The throwaway folders of --sample (5.1 review): its own pair, never the operator's; the leftovers of a killed sample server go at the next start. public sealed class SampleFoldersTests : IDisposable {