From 9875ab64eb16942477330e87e2cabe0783c37948 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 30 Sep 2026 12:48:31 +0200 Subject: [PATCH] =?UTF-8?q?5.1:=20impostazioni=20tutte=20dall'interfaccia?= =?UTF-8?q?=20e=20applicate=20dal=20bot=20in=20esecuzione,=20segreti=20cif?= =?UTF-8?q?rati=20con=20la=20password,=20niente=20Paper,=20conto=20legato?= =?UTF-8?q?=20alla=20modalit=C3=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Perché: il proprietario vuole che il container abbia una sola variabile (la password dell'interfaccia) e che ogni impostazione si faccia dalla pagina web e valga subito. Fino alla 5.0 un salvataggio scriveva solo il file (il motore lo leggeva al riavvio del container), le variabili d'ambiente sovrascrivevano a ogni avvio le scelte fatte nell'interfaccia, e modalità e conto erano due impostazioni separate: Demo + real mandava ordini al conto reale senza il cancello del Live. Cosa cambia: - Paper rimosso ovunque (enum, PaperBroker, paperStartingBalance/paperSlippagePips, catalogo): un file con "Paper" si legge come Demo con un avviso. Le righe storiche del ledger con mode=Paper restano come sono. - Modalità e conto fusi: run.executionMode Demo | Live sceglie anche il conto; etoro.environment esce dal file (regola di fusione per i file della 5.0: Live solo se Live e real, altrimenti Demo con un avviso) e sparisce al primo salvataggio. - Cancello del Live: interruttore allowLive più la frase CONFERMO LIVE scritta nell'interfaccia (AVVIA con confirm, POST /api/settings con confirm). Niente più ENCELADO_CONFIRM_LIVE né --confirm-live; il Live non parte mai da solo (allarme liveNeedsConfirmation e avviso Telegram); BotSupervisor.StartAsync(liveConfirmed) senza flag appiccicoso; il cambio di conto è rifiutato con basket aperti, in attesa o ordini senza esito. - Password: ENCELADO_PASSWORD (alias deprecato ENCELADO_WEB_TOKEN), campo password del login (token ancora accettato), cookie encelado_session = HMAC derivato dalla password (mai la password), POST /logout, Bearer per gli script, confronti a tempo costante e un secondo di attesa dopo una password errata. - SecretStore: secrets.enc (AES-256-GCM, PBKDF2-SHA256 600 000 iterazioni, sale conservato, nonce nuovo a ogni scrittura, header autenticato) con le chiavi eToro del conto demo e del conto reale e il token Telegram; senza password una chiave locale in secrets.key, migrata alla password quando compare; password cambiata = bloccato, sblocco con la precedente o ricomincia con un .bak. I segreti non entrano mai nella BotConfig condivisa: motore e storico costruiscono EtoroOptions privati. - Importazione una tantum dalla 5.0 (import-5.1.json, idempotente): chiavi e token nel deposito solo negli slot vuoti, il vecchio etoro.keys.enc importato e rinominato .migrato, impostazioni solo se diverse dal default di fabbrica e il file lo conserva ancora; poi ogni variabile rimasta è ignorata ed elencata nel log, in /api/settings e nello snapshot (ignoredEnv). Il loader non legge più l'ambiente. - run.autostart (predefinito acceso) al posto di ENCELADO_AUTOSTART; --no-autostart resta per lo sviluppo. - Preset solo in strategy.json, scelto in Impostazioni ▸ Strategia: comando preset tolto da motore, web e console; i basket aperti tengono zStop e aggiunte con cui sono entrati (salvati in BasketPosition, PendingEntry e nello stato). - Applicazione a caldo: SettingsRuntime con un lock di scrittura, catalogo con file (config/strategy) e momento d'effetto (immediate/engine/restart), ConfigWriter con encoder rilassato e cancellazione di chiavi (e le righe _ di documentazione aggiornate), BotConfig.CopyFrom, comando ApplySettings sul thread di decisione (CopyFrom/SameStructure della strategia, BasketDecider.Reload, impronta ricalcolata e riga "configurazione" nel ledger), intervalli letti a ogni tick, timeout delle richieste per richiesta, basket spenti che continuano a gestire le uscite, pausa persistita nello stato, NotifierHub che accende, spegne e cambia Telegram e il poller dei comandi, Log.Reconfigure, LogBuffer.Resize, HistoryService.Invalidate, riavvio automatico del motore senza chiudere i basket per i cambi che lo richiedono (409 needsPhrase prima di scrivere se riparte in Live). - API di Impostazioni e Segreti secondo docs/API.md (campi aggiunti documentati lì). - Deploy: template Unraid con porta, /config, /data e la sola "Password interfaccia"; compose con la sola ENCELADO_PASSWORD (sviluppo); Dockerfile senza ENCELADO_AUTOSTART; launch.json e run-dev con la stessa password del compose; run-docker senza PUID/PGID. - 75 test nuovi o riscritti (333 in tutto): deposito dei segreti, importazione, password, runtime con un motore finto, strategia a caldo, uscite dei basket spenti, log e notifiche, avvio automatico, scrittura della configurazione. Co-Authored-By: Claude Opus 5.5 --- Encelado/.vscode/launch.json | 11 +- Encelado/Dockerfile | 9 +- Encelado/config/encelado.json | 27 +- Encelado/config/strategy.json | 4 +- Encelado/deploy/unraid/encelado.xml | 20 +- Encelado/docker-compose.yml | 29 +- Encelado/docs/API.md | 420 +++++++++ Encelado/scripts/run-dev.ps1 | 13 +- Encelado/scripts/run-dev.sh | 6 +- Encelado/scripts/run-docker.ps1 | 13 +- Encelado/scripts/run-docker.sh | 6 +- .../Baskets/Backtest/BasketBacktest.cs | 2 +- .../Baskets/Backtest/BasketTrials.cs | 67 +- .../Encelado.Core/Baskets/BasketDecider.cs | 36 +- .../Encelado.Core/Baskets/BasketExecutor.cs | 4 + .../Encelado.Core/Baskets/BasketPosition.cs | 10 + .../Encelado.Core/Baskets/BasketSlotPolicy.cs | 17 + .../Baskets/BasketStrategyConfig.cs | 142 ++- .../Encelado.Core/Baskets/ExecutionMode.cs | 53 +- .../Baskets/Learning/ThompsonBandit.cs | 5 +- .../src/Encelado.Core/Baskets/PendingEntry.cs | 14 + Encelado/src/Encelado.Core/Broker/Broker.cs | 12 +- .../src/Encelado.Core/Broker/PaperBroker.cs | 560 ------------ .../Encelado.Core/Notifications/INotifier.cs | 9 + .../Notifications/NotifierHub.cs | 183 ++++ .../Notifications/TelegramNotifier.cs | 140 ++- .../Baskets/BasketEngine.Commands.cs | 108 ++- .../Baskets/BasketEngine.Realized.cs | 5 - .../Baskets/BasketEngine.Snapshot.cs | 25 +- .../Baskets/BasketEngine.State.cs | 28 + .../Encelado.Engine/Baskets/BasketEngine.cs | 109 ++- .../Encelado.Engine/Baskets/HeadlessRunner.cs | 8 +- .../Encelado.Engine/Baskets/HistoryService.cs | 72 +- .../Baskets/TelegramCommands.cs | 22 - .../Encelado.Engine/Configuration/AppPaths.cs | 8 +- .../Configuration/BotConfig.cs | 109 ++- .../Configuration/ConfigDefaults.cs | 35 +- .../Configuration/ConfigLoader.cs | 282 ++++-- .../Configuration/ConfigWriter.cs | 205 ++++- .../Configuration/EnvironmentImport.cs | 358 ++++++++ .../Configuration/InterfacePassword.cs | 54 ++ .../Encelado.Engine/Configuration/KeyStore.cs | 77 +- .../Configuration/SecretStore.cs | 659 ++++++++++++++ .../src/Encelado.Engine/Engine/BotSnapshot.cs | 34 +- .../Encelado.Engine/Engine/BotSupervisor.cs | 100 ++- .../src/Encelado.Engine/Engine/IEngine.cs | 12 +- .../Encelado.Engine/Engine/SnapshotJson.cs | 12 + Encelado/src/Encelado.Engine/Logging/Log.cs | 39 +- .../Settings/AccountActivity.cs | 85 ++ .../Settings/AutostartPolicy.cs | 52 ++ .../Encelado.Engine/Settings/SettingField.cs | 282 +++--- .../Settings/SettingsCatalogue.cs | 672 ++++++++++----- .../Settings/SettingsRuntime.cs | 811 ++++++++++++++++++ .../Settings/SettingsService.cs | 355 +++++--- .../Encelado.Engine/Settings/StrategyCache.cs | 83 ++ Encelado/src/Encelado.Etoro/EtoroHttp.cs | 12 +- Encelado/src/Encelado.Etoro/EtoroOptions.cs | 12 +- Encelado/src/Encelado.Server/Program.cs | 184 ++-- Encelado/src/Encelado.Server/Web/LogBuffer.cs | 39 +- .../src/Encelado.Server/Web/SettingsApi.cs | 162 ++++ Encelado/src/Encelado.Server/Web/WebHost.cs | 283 +++--- Encelado/tests/Encelado.Tests/BasketTests.cs | 8 +- .../Encelado.Tests/ConfigurationTests.cs | 389 ++++++++- .../tests/Encelado.Tests/CorrectionTests.cs | 2 + .../Encelado.Tests/EnvironmentImportTests.cs | 222 +++++ .../tests/Encelado.Tests/HotApplyTests.cs | 358 ++++++++ .../tests/Encelado.Tests/KeyStoreTests.cs | 150 ---- .../tests/Encelado.Tests/SecretStoreTests.cs | 271 ++++++ .../Encelado.Tests/SettingsRuntimeTests.cs | 468 ++++++++++ Encelado/tests/Encelado.Tests/WebTests.cs | 123 ++- 70 files changed, 7208 insertions(+), 1988 deletions(-) create mode 100644 Encelado/docs/API.md create mode 100644 Encelado/src/Encelado.Core/Baskets/BasketSlotPolicy.cs delete mode 100644 Encelado/src/Encelado.Core/Broker/PaperBroker.cs create mode 100644 Encelado/src/Encelado.Core/Notifications/NotifierHub.cs create mode 100644 Encelado/src/Encelado.Engine/Configuration/EnvironmentImport.cs create mode 100644 Encelado/src/Encelado.Engine/Configuration/InterfacePassword.cs create mode 100644 Encelado/src/Encelado.Engine/Configuration/SecretStore.cs create mode 100644 Encelado/src/Encelado.Engine/Settings/AccountActivity.cs create mode 100644 Encelado/src/Encelado.Engine/Settings/AutostartPolicy.cs create mode 100644 Encelado/src/Encelado.Engine/Settings/SettingsRuntime.cs create mode 100644 Encelado/src/Encelado.Engine/Settings/StrategyCache.cs create mode 100644 Encelado/src/Encelado.Server/Web/SettingsApi.cs create mode 100644 Encelado/tests/Encelado.Tests/EnvironmentImportTests.cs create mode 100644 Encelado/tests/Encelado.Tests/HotApplyTests.cs delete mode 100644 Encelado/tests/Encelado.Tests/KeyStoreTests.cs create mode 100644 Encelado/tests/Encelado.Tests/SecretStoreTests.cs create mode 100644 Encelado/tests/Encelado.Tests/SettingsRuntimeTests.cs diff --git a/Encelado/.vscode/launch.json b/Encelado/.vscode/launch.json index 6b541c1..c1ea929 100644 --- a/Encelado/.vscode/launch.json +++ b/Encelado/.vscode/launch.json @@ -2,11 +2,11 @@ // F5 avvia il server (motore + interfaccia web) come processo locale, fuori dal // container, con configurazione e dati nella sandbox deploy/local (ignorata da git, // stesse cartelle che il compose monta come /config e /data). Il browser si apre da - // solo appena Kestrel è in ascolto; senza token il server ascolta solo su localhost e - // non chiede il login. "Encelado (campione)" serve l'interfaccia con dati finti, senza - // chiavi né mercato: è quello che si usa per lavorare sulle pagine. - // Le chiavi eToro: variabili ETORO_API_KEY/ETORO_USER_KEY nell'ambiente di VS Code, - // oppure Impostazioni ▸ Chiavi eToro con ENCELADO_KEY_PASSPHRASE impostata qui sotto. + // solo appena Kestrel è in ascolto. La password dell'interfaccia è "sviluppo", la + // stessa del compose: i segreti cifrati della sandbox (chiavi eToro, token Telegram, + // inseriti da Impostazioni) restano leggibili sia da F5 sia dal container. + // "Encelado (campione)" serve l'interfaccia con dati finti, senza chiavi né mercato e + // senza password: è quello che si usa per lavorare sulle pagine. "version": "0.2.0", "configurations": [ { @@ -21,6 +21,7 @@ "stopAtEntry": false, "env": { "ENCELADO_WEB_PORT": "8080", + "ENCELADO_PASSWORD": "sviluppo", "ENCELADO_CONFIG_DIR": "${workspaceFolder}/deploy/local/config", "ENCELADO_DATA_DIR": "${workspaceFolder}/deploy/local/data", "DOTNET_ENVIRONMENT": "Development" diff --git a/Encelado/Dockerfile b/Encelado/Dockerfile index 0600be6..07215a4 100644 --- a/Encelado/Dockerfile +++ b/Encelado/Dockerfile @@ -7,8 +7,12 @@ # non trimmed: il server ospita ASP.NET Core minimal e non è AOT). Il runtime è # l'immagine ufficiale aspnet, con gosu per scendere ai PUID/PGID di Unraid. # -# docker build -t 192.168.30.23:3000/alby96/encelado:5.0.0 --build-arg GIT_COMMIT=$(git rev-parse --short=12 HEAD) . -# docker run -p 8080:8080 -v ./config:/config -v ./data:/data -e TZ=Europe/Rome 192.168.30.23:3000/alby96/encelado:5.0.0 +# docker build -t 192.168.30.23:3000/alby96/encelado:5.1.0 --build-arg GIT_COMMIT=$(git rev-parse --short=12 HEAD) . +# docker run -p 8080:8080 -v ./config:/config -v ./data:/data -e ENCELADO_PASSWORD=… 192.168.30.23:3000/alby96/encelado:5.1.0 +# +# L'unica variabile da dare al container è ENCELADO_PASSWORD (la password +# dell'interfaccia): tutto il resto si imposta dall'interfaccia. Le ENV qui sotto sono +# interne all'immagine (PUID/PGID/TZ restano i default di Unraid e UTC). # # Vedi docs/DOCKER.md per volumi, variabili, healthcheck e aggiornamento. @@ -62,7 +66,6 @@ RUN apt-get update \ ENV ENCELADO_IN_CONTAINER=1 \ ENCELADO_WEB_PORT=8080 \ - ENCELADO_AUTOSTART=1 \ DOTNET_gcServer=1 \ DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 \ ASPNETCORE_URLS= \ diff --git a/Encelado/config/encelado.json b/Encelado/config/encelado.json index 28ee1c2..3cd78f1 100644 --- a/Encelado/config/encelado.json +++ b/Encelado/config/encelado.json @@ -1,39 +1,38 @@ { - "_commento": "Configurazione di Encelado — Correlation Baskets su eToro (CFD forex). Le chiavi con il prefisso _ sono documentazione e vengono ignorate. I parametri della strategia (basket, preset, soglie, rischio) stanno in strategy.json accanto a questo file. Le chiavi API non stanno qui: si inseriscono dalla finestra e vivono cifrate in %LOCALAPPDATA%\\Encelado\\etoro.dat, oppure nelle variabili d'ambiente ETORO_API_KEY e ETORO_USER_KEY.", + "_commento": "Configurazione di Encelado — Correlation Baskets su eToro (CFD forex). Si modifica da Impostazioni nell'interfaccia web, che applica subito tutto quello che può (quando serve riavvia il motore da sé, senza chiudere i basket). Le chiavi con il prefisso _ sono documentazione e vengono ignorate. I parametri della strategia (basket, preset, soglie, rischio) stanno in strategy.json accanto a questo file. Le chiavi eToro e il token Telegram non stanno qui: si inseriscono da Impostazioni e vivono cifrati in secrets.enc con la password dell'interfaccia.", "etoro": { - "_note": "eToro Public API. environment = demo oppure real: chiavi e rotte sono diverse, e l'ambiente attivo è sempre visibile nella finestra.", - "environment": "demo", + "_note": "eToro Public API. Il conto segue run.executionMode: Demo = conto demo, Live = conto reale; chiavi e rotte dei due conti sono diverse e il conto attivo è sempre visibile nell'interfaccia.", "baseUrl": "https://public-api.etoro.com", + "_requestTimeoutSeconds": "Oltre questo tempo una richiesta HTTP a eToro viene abbandonata (e, se era una lettura, ritentata).", "requestTimeoutSeconds": 20, "_fillTimeoutSeconds": "Quanto attendere l'esito di un ordine (eToro lo lavora in modo asincrono) prima di trattarlo come non confermato e riconciliare. È anche il timeout della seconda gamba (leg-risk).", "fillTimeoutSeconds": 5 }, "run": { - "_executionMode": "Paper = simulatore locale sopra le quotazioni reali (nessun ordine sul conto). Demo = conto demo di eToro: ordini veri, denaro virtuale, il bot apre e chiude da solo. Live = conto reale: richiede allowLive = true e la frase CONFERMO LIVE a ogni avvio. Nessuna modalità chiede l'approvazione dei singoli ordini (decisione D-20).", + "_executionMode": "Demo = conto demo di eToro: ordini veri, denaro virtuale, il bot apre e chiude da solo. Live = conto reale: richiede allowLive = true e la frase CONFERMO LIVE scritta nell'interfaccia a ogni avvio; in Live il motore non parte mai da solo. Il cambio di conto è rifiutato finché ci sono basket aperti o ordini in sospeso. Nessuna modalità chiede l'approvazione dei singoli ordini (decisione D-20).", "executionMode": "Demo", "allowLive": false, + "_autostart": "true = all'avvio del container il motore parte da solo (mai in Live, che aspetta AVVIA con la frase). false = il motore parte solo con AVVIA.", + "autostart": true, "_pollSeconds": "Secondi fra due letture delle quotazioni (una richiesta per tutti gli strumenti). 3 s = 20 richieste al minuto su una quota di 120: resta spazio per candele e costi.", "pollSeconds": 3, - "_statusSeconds": "Ogni quanti secondi il bot scrive una riga di stato nel log (e sulla console in headless).", + "_statusSeconds": "Ogni quanti secondi il bot scrive una riga di stato nel log (e sulla console).", "statusSeconds": 60, - "_closeOnShutdown": "true = fermare il bot chiude i basket aperti a mercato. false = restano sul conto con gli stop nativi sul server, senza nessuno che applichi il take-profit o lo stop di basket finché il bot non riparte.", + "_closeOnShutdown": "true = fermare il bot chiude i basket aperti a mercato. false = restano sul conto con gli stop nativi sul server, senza nessuno che applichi il take-profit o lo stop di basket finché il bot non riparte. Un riavvio automatico dopo un cambio delle impostazioni non chiude mai niente.", "closeOnShutdown": false, "strategyFile": "strategy.json", - "_cartelle": "Relative alla cartella di questo file: data (mercato, calendario, notizie, ledger, modelli), knowledge (calibrazione, proposte, registri), reports.", + "_cartelle": "Relative alla cartella di questo file: data (mercato, calendario, notizie, ledger, modelli), knowledge (calibrazione, proposte, registri), reports. Nel container stanno in /data.", "dataDirectory": "data", "knowledgeDirectory": "knowledge", - "reportsDirectory": "reports", - "_paper": "Solo per executionMode = Paper: saldo iniziale del simulatore e slippage per gamba oltre lo spread reale del momento.", - "paperStartingBalance": 10000, - "paperSlippagePips": 0.3 + "reportsDirectory": "reports" }, "ui": { - "_timeZone": "Fuso orario con cui l'interfaccia mostra gli orari. 'computer' = quello del sistema (nel container la variabile TZ); 'UTC'; oppure un id IANA (es. 'Europe/Rome'). Il file di log porta l'offset, il ledger è in UTC: cambiare questo valore non tocca nessun file.", + "_timeZone": "Fuso degli orari scritti dal server (righe di attività, riga di stato): 'computer' = quello del sistema; 'UTC'; oppure un id IANA (es. 'Europe/Rome'). Gli orologi dell'interfaccia usano il fuso del browser; il file di log porta l'offset e il ledger è in UTC.", "timeZone": "computer", - "_displayCurrency": "Valuta in cui l'interfaccia, Telegram e le esportazioni mostrano gli importi (USD, EUR, GBP, CHF, JPY, AUD, CAD, NZD). I tassi vengono dalle quotazioni eToro già in polling; ledger e decisioni restano in USD. Anche ENCELADO_DISPLAY_CURRENCY.", + "_displayCurrency": "Valuta in cui l'interfaccia mostra gli importi (USD, EUR, GBP, CHF, JPY, AUD, CAD, NZD). I tassi vengono dalle quotazioni eToro già in polling; ledger e decisioni restano in USD.", "displayCurrency": "USD", "_theme": "dark oppure light.", "theme": "dark", @@ -57,7 +56,7 @@ }, "notifications": { - "_telegram": "Notifiche e comandi su Telegram (5.0). Il token del bot NON si scrive qui: variabile d'ambiente TELEGRAM_BOT_TOKEN (e TELEGRAM_CHAT_ID, che ha la precedenza su chatId). hourlyStatus = stato allo scoccare di ogni ora UTC; eventAlerts = aperture, chiusure, ordini risolti, kill-switch, recupero, errori; dailySummaryUtcHour = ora UTC del riepilogo giornaliero (negativo = spento); commands = risposte ai comandi /stato, /posizioni, /storico, /pausa, /riprendi, /chiudi, /kill CONFERMO, /reset dalla sola chat autorizzata.", + "_telegram": "Notifiche e comandi su Telegram. Il token del bot si inserisce da Impostazioni ▸ Notifiche Telegram e vive cifrato in secrets.enc, mai in questo file; chatId è la sola chat che riceve i messaggi e può dare comandi. hourlyStatus = stato allo scoccare di ogni ora UTC; eventAlerts = aperture, chiusure, ordini risolti, kill-switch, recupero, errori; dailySummaryUtcHour = ora UTC del riepilogo giornaliero (negativo = spento); commands = risposte ai comandi /stato, /posizioni, /storico, /pausa, /riprendi, /chiudi, /kill CONFERMO, /reset dalla sola chat autorizzata.", "telegram": { "enabled": false, "chatId": "", diff --git a/Encelado/config/strategy.json b/Encelado/config/strategy.json index 3826f95..3e9e22a 100644 --- a/Encelado/config/strategy.json +++ b/Encelado/config/strategy.json @@ -1,14 +1,14 @@ { "_comment": "Encelado — strategia Correlation Baskets su eToro. Cinque basket di due coppie forex correlate: si entra quando il cross sintetico diverge (z-score), si esce quando converge o al take-profit di basket in pip; lo stop di basket è obbligatorio. Ogni chiave con '_' davanti è documentazione.", - "_preset": "Conservative | Moderate | Aggressive. Fissa zIn, riskPerBasketPct, maxBaskets, tpPips, maxAdds, zStop; si cambia a caldo dalla finestra senza toccare i basket aperti. Le chiavi omonime qui sotto, se presenti, sovrascrivono il preset.", + "_preset": "Conservative | Moderate | Aggressive. Fissa zIn, riskPerBasketPct, maxBaskets, tpPips, maxAdds, zStop. Si sceglie in Impostazioni ▸ Strategia e il bot lo applica subito ai basket nuovi: quelli già aperti tengono take-profit, perdita massima, zStop e aggiunte con cui sono entrati. Le chiavi omonime qui sotto, se presenti, sovrascrivono il preset.", "preset": "Moderate", "_signalMode": "ZScoreSynthetic (default, |z| >= zIn sul cross sintetico) oppure PipDivergence (fedele all'interfaccia Titany: divergenza in pip dall'ancora, dIn).", "signalMode": "ZScoreSynthetic", "_exitMode": "First = la prima fra TP in pip e rientro dello z; FixedPips = solo TP in pip lordi; ZReturn = solo |z| <= zOut.", "exitMode": "First", - "_averagingMode": "Off | AddOnce | Grid. Off in live; AddOnce in paper. Moltiplicatore di lotto sempre 1,0 (niente martingala).", + "_averagingMode": "Off | AddOnce | Grid. Off di fabbrica; AddOnce ammette una sola aggiunta per basket, Grid fino a maxAdds. Moltiplicatore di lotto sempre 1,0 (niente martingala).", "averagingMode": "Off", "tpMode": "Pips", "_sameCrossPolicy": "I basket 4 e 5 sono entrambi EURCAD: Exclusive = uno solo aperto per volta; Half = entrambi a metà size.", diff --git a/Encelado/deploy/unraid/encelado.xml b/Encelado/deploy/unraid/encelado.xml index cad9b98..98a1a0d 100644 --- a/Encelado/deploy/unraid/encelado.xml +++ b/Encelado/deploy/unraid/encelado.xml @@ -9,7 +9,7 @@ false http://192.168.30.23:3000/Alby96/Encelado/issues http://192.168.30.23:3000/Alby96/Encelado - Encelado: bot di trading "Correlation Baskets" su eToro (Public API). Motore, ledger e interfaccia web Material 3 in un solo container. Configurazione in /config (encelado.json, strategy.json, chiavi cifrate), dati in /data (ledger, stato, barre, conoscenza, rapporti, log). Le chiavi eToro si mettono nelle variabili ETORO_API_KEY e ETORO_USER_KEY oppure si salvano dall'interfaccia (cifrate con ENCELADO_KEY_PASSPHRASE). Modalita' Live solo con ENCELADO_EXECUTION_MODE=Live, ETORO_ENVIRONMENT=real e la frase CONFERMO LIVE in ENCELADO_CONFIRM_LIVE. + Encelado: bot di trading "Correlation Baskets" su eToro (Public API). Motore, ledger e interfaccia web in un solo container. L'unica cosa da scegliere qui e' la password dell'interfaccia: tutto il resto (conto demo o reale, chiavi eToro dei due conti, Telegram, strategia, valuta, log) si imposta dalla pagina Impostazioni, e il bot applica subito ogni cambio. Le chiavi e il token Telegram restano cifrati in /config con questa password: se la cambi, l'interfaccia chiede quella precedente per riaprirli. La modalita' Live non parte mai da sola: serve AVVIA e la frase CONFERMO LIVE. Configurazione in /config, dati in /data (ledger, stato, barre, conoscenza, rapporti, log). Tools: Productivity: http://[IP]:[PORT:8080]/ http://192.168.30.23:3000/Alby96/Encelado/raw/branch/main/deploy/unraid/encelado.xml @@ -23,21 +23,7 @@ 8080 - /mnt/user/appdata/encelado/config + /mnt/user/appdata/encelado/config /mnt/user/appdata/encelado/data - - - - demo - Demo - - - 8080 - USD - - - - Europe/Rome - 99 - 100 + diff --git a/Encelado/docker-compose.yml b/Encelado/docker-compose.yml index 39a9a3b..a386a0c 100644 --- a/Encelado/docker-compose.yml +++ b/Encelado/docker-compose.yml @@ -2,14 +2,15 @@ # radice, cartelle di configurazione e dati sotto deploy/local (ignorate da git). # # docker compose up --build # costruisce e avvia, log a video (Ctrl+C = stop pulito) -# docker compose up -d --build # in background → http://localhost:8080/ (token "sviluppo") +# docker compose up -d --build # in background → http://localhost:8080/ (password "sviluppo") # docker compose logs -f encelado # segue il log # docker compose down # ferma (SIGTERM: stop pulito del motore) # Oppure: scripts/run-docker.ps1 (o .sh), che fa le stesse cose e stampa l'indirizzo. # -# Le chiavi eToro e il token Telegram NON stanno qui: mettili in un file .env -# accanto a questo (ignorato da git) con ETORO_API_KEY=…, ETORO_USER_KEY=…, -# TELEGRAM_BOT_TOKEN=…, TELEGRAM_CHAT_ID=…, ENCELADO_WEB_TOKEN=… +# L'unica variabile è la password dell'interfaccia (ENCELADO_PASSWORD, di default +# "sviluppo", la stessa di F5 e degli script, così i segreti cifrati in deploy/local +# restano leggibili in entrambi i modi; una vera in un file .env accanto a questo). +# Conto, chiavi eToro, Telegram e tutto il resto si impostano dall'interfaccia. # Per Unraid usa invece il template in deploy/unraid/encelado.xml. services: @@ -28,23 +29,5 @@ services: - ./deploy/local/config:/config - ./deploy/local/data:/data environment: - TZ: ${TZ:-Europe/Rome} - PUID: ${PUID:-1000} - PGID: ${PGID:-1000} - # demo | real — l'ambiente eToro; real richiede anche ENCELADO_EXECUTION_MODE=Live - ETORO_ENVIRONMENT: ${ETORO_ENVIRONMENT:-demo} - # Paper | Demo | Live - ENCELADO_EXECUTION_MODE: ${ENCELADO_EXECUTION_MODE:-Demo} - # Solo per Live: la frase esatta «CONFERMO LIVE», altrimenti il bot non parte - ENCELADO_CONFIRM_LIVE: ${ENCELADO_CONFIRM_LIVE:-} - ENCELADO_DISPLAY_CURRENCY: ${ENCELADO_DISPLAY_CURRENCY:-USD} - # Senza token l'interfaccia è raggiungibile solo da localhost del container: - # per usarla dal browser il token serve. "sviluppo" è il default delle prove - # in locale; in .env mettine uno vero. - ENCELADO_WEB_TOKEN: ${ENCELADO_WEB_TOKEN:-sviluppo} - ENCELADO_KEY_PASSPHRASE: ${ENCELADO_KEY_PASSPHRASE:-} - ETORO_API_KEY: ${ETORO_API_KEY:-} - ETORO_USER_KEY: ${ETORO_USER_KEY:-} - TELEGRAM_BOT_TOKEN: ${TELEGRAM_BOT_TOKEN:-} - TELEGRAM_CHAT_ID: ${TELEGRAM_CHAT_ID:-} + ENCELADO_PASSWORD: ${ENCELADO_PASSWORD:-sviluppo} stop_grace_period: 45s diff --git a/Encelado/docs/API.md b/Encelado/docs/API.md new file mode 100644 index 0000000..80ef88c --- /dev/null +++ b/Encelado/docs/API.md @@ -0,0 +1,420 @@ +# API dell'interfaccia web (5.1) + +Aggiornato: 2026-09-30. È il contratto fra il server (`src/Encelado.Server/Web`) e l'interfaccia (`Web/wwwroot`): i nomi dei campi qui sono quelli veri. Chi cambia un campo aggiorna questo file nello stesso commit. + +## Convenzioni + +- JSON scritto a mano con `Utf8JsonWriter` (nessuna serializzazione per riflessione); nomi dei campi in inglese, camelCase. +- **Importi in USD**: la conversione nella valuta di visualizzazione la fa solo il browser, con `fxRates` del tick. +- **Tempi** in ISO-8601 UTC (`"O"`, es. `2026-09-30T08:15:04.1230000Z`); il browser li mostra nel proprio fuso. +- 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`. Senza password il server ascolta solo su localhost e non chiede niente. +- `--sample`: ogni rotta risponde con dati d'esempio realistici e coerenti fra loro (nessuna chiave, nessun mercato), per lavorare sulle pagine e fotografarle. + +## File statici + +Ogni file incorporato sotto `wwwroot/` è servito al suo percorso (`/css/app.css`, `/js/app.js`, `/js/pages/dashboard.js`, `/img/…`), con il tipo dal suffisso (`.html`, `.css`, `.js` come `text/javascript`, `.svg`, `.webmanifest`, `.png`, `.ico`), `ETag` e `Cache-Control: no-cache` (la richiesta con `If-None-Match` uguale riceve **304**). `/` → `index.html`, `/login` → `login.html`. + +## 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: dopo un secondo di attesa, **401** con la pagina di login e il messaggio (`Hot swap of the preset: open baskets keep the numbers they were opened with. - public void SetPreset(PresetName name) => _preset = _cfg.Effective(name); + /// + /// Takes the configuration again after it changed in place (a save in Impostazioni, + /// applied on the decision thread): the preset in force is recomputed from the file's + /// preset and overrides and the cached half-lives are recomputed at the next bar (the + /// window may have changed). The PipDivergence anchors are dropped only when asked — + /// when the signal mode or the anchor period changed —, since a new anchor moves the + /// signal. Open baskets keep the z stop, the adds, the take-profit and the maximum loss + /// they entered with (they travel in the ). + /// + public void Reload(bool resetAnchors = false) + { + _preset = _cfg.Effective(); + _halfLives.Clear(); + if (resetAnchors) + { + _anchors.Clear(); + } + } /// Bars of the timeframe in one day (M15 → 96). public const int BarsPerDay = 96; @@ -714,9 +730,11 @@ public sealed class BasketDecider } // z stop can be judged on any quote too; correlation and time only on bar close. - if (double.IsFinite(e.Z) && (p.BuyCross ? e.Z <= -_preset.ZStop : e.Z >= _preset.ZStop)) + // The stop is the one the basket entered with: a preset changed since then does not move it. + double zStop = double.IsFinite(p.ZStop) && p.ZStop > 0 ? p.ZStop : _preset.ZStop; + if (double.IsFinite(e.Z) && (p.BuyCross ? e.Z <= -zStop : e.Z >= zStop)) { - return Exit(e, ["stop_z"], F($"stop di basket: z {e.Z:+0.00;-0.00} oltre ±{_preset.ZStop:0.00} ({e.PipsOpen:+0.0;-0.0} pip, netto {Fmt2(e.PnlOpenUsd)} USD)")); + return Exit(e, ["stop_z"], F($"stop di basket: z {e.Z:+0.00;-0.00} oltre ±{zStop:0.00} ({e.PipsOpen:+0.0;-0.0} pip, netto {Fmt2(e.PnlOpenUsd)} USD)")); } if (!ctx.IsBarClose) @@ -742,16 +760,18 @@ public sealed class BasketDecider p.BarsWithBrokenCorrelation = 0; } - // Averaging (§5.5): only when |z| grew by GridStepZ since the last entry, within MaxAdds. + // Averaging (§5.5): only when |z| grew by GridStepZ since the last entry, within the + // adds the basket entered with. + int presetAdds = p.MaxAdds >= 0 ? p.MaxAdds : _preset.MaxAdds; int maxAdds = _cfg.AveragingMode switch { AveragingMode.Off => 0, - AveragingMode.AddOnce => Math.Min(1, _preset.MaxAdds), - _ => _preset.MaxAdds, + AveragingMode.AddOnce => Math.Min(1, presetAdds), + _ => presetAdds, }; if (maxAdds > 0 && p.Adds < maxAdds && double.IsFinite(e.Z) && - Math.Abs(e.Z) - Math.Abs(p.LastAddZ) >= _cfg.GridStepZ && Math.Abs(e.Z) < _preset.ZStop && + Math.Abs(e.Z) - Math.Abs(p.LastAddZ) >= _cfg.GridStepZ && Math.Abs(e.Z) < zStop && ctx.EntriesBlockedReason is null && !ctx.DailyLossHit) { double scale = Math.Pow(_cfg.LotMultiplier, p.Adds + 1); diff --git a/Encelado/src/Encelado.Core/Baskets/BasketExecutor.cs b/Encelado/src/Encelado.Core/Baskets/BasketExecutor.cs index 6592f90..0cd5048 100644 --- a/Encelado/src/Encelado.Core/Baskets/BasketExecutor.cs +++ b/Encelado/src/Encelado.Core/Baskets/BasketExecutor.cs @@ -125,6 +125,8 @@ public sealed class BasketExecutor UnitsB = sizing.UnitsB, TpPips = _cfg.TpMode == TpMode.AtrMultiple && double.IsFinite(decision.Evaluation.AtrPipsA) ? Math.Max(1, _cfg.TpAtrMultiple * decision.Evaluation.AtrPipsA) : preset.TpPips, MaxLossUsd = ctx.Equity * _cfg.MaxLossPerBasketPct / 100.0, + ZStop = preset.ZStop, + MaxAdds = preset.MaxAdds, EntryCostPips = decision.Cost?.CostPips ?? double.NaN, EquityAtEntry = ctx.Equity, Motivazione = decision.Motivazione, @@ -307,6 +309,8 @@ public sealed class BasketExecutor EntryCostPips = plan.EntryCostPips, TpPips = plan.TpPips, MaxLossUsd = plan.MaxLossUsd, + ZStop = plan.ZStop, + MaxAdds = plan.MaxAdds, EquityAtEntry = plan.EquityAtEntry, EntryMotivazione = plan.Motivazione, }; diff --git a/Encelado/src/Encelado.Core/Baskets/BasketPosition.cs b/Encelado/src/Encelado.Core/Baskets/BasketPosition.cs index baecc53..b4542be 100644 --- a/Encelado/src/Encelado.Core/Baskets/BasketPosition.cs +++ b/Encelado/src/Encelado.Core/Baskets/BasketPosition.cs @@ -188,6 +188,16 @@ public sealed class BasketPosition public double MaxLossUsd { get; init; } + /// + /// The z stop of the preset in force at entry: a preset changed later does not move it + /// (5.1, decision C10). NaN for a basket saved by a version before 5.1, which falls back + /// on the preset in force. + /// + public double ZStop { get; init; } = double.NaN; + + /// The adds allowed by the preset in force at entry; −1 for a basket saved before 5.1 (the preset in force decides). + public int MaxAdds { get; init; } = -1; + public double EquityAtEntry { get; init; } public int BarsWithBrokenCorrelation { get; set; } diff --git a/Encelado/src/Encelado.Core/Baskets/BasketSlotPolicy.cs b/Encelado/src/Encelado.Core/Baskets/BasketSlotPolicy.cs new file mode 100644 index 0000000..8184099 --- /dev/null +++ b/Encelado/src/Encelado.Core/Baskets/BasketSlotPolicy.cs @@ -0,0 +1,17 @@ +namespace Encelado.Core.Baskets; + +/// +/// What a basket switched off in the strategy still does (5.1). Switching a basket off +/// stops its entries, never its exits: a basket that is open when the switch goes off (or +/// that the saved state brings back into a disabled slot) is still watched until it +/// closes by its own rules — take-profit, stops, time — instead of being left to the +/// native stop-loss on the venue alone. +/// +public static class BasketSlotPolicy +{ + /// Whether the engine evaluates the slot at all: always when enabled; when disabled, only while it holds a basket. + public static bool Evaluates(bool enabled, bool hasPosition) => enabled || hasPosition; + + /// Whether a decision may be carried out on the slot: exits and holds always; entries and adds only when enabled. + public static bool MayExecute(bool enabled, DecisionKind kind) => enabled || kind is not (DecisionKind.Enter or DecisionKind.Add); +} diff --git a/Encelado/src/Encelado.Core/Baskets/BasketStrategyConfig.cs b/Encelado/src/Encelado.Core/Baskets/BasketStrategyConfig.cs index 08f757a..56592e4 100644 --- a/Encelado/src/Encelado.Core/Baskets/BasketStrategyConfig.cs +++ b/Encelado/src/Encelado.Core/Baskets/BasketStrategyConfig.cs @@ -143,8 +143,11 @@ public sealed class BasketDefinition /// /// Every parameter of the strategy, from strategy.json. Values not in the file take -/// the defaults written in the specification; the active preset supplies six of them and -/// can be swapped at runtime without touching open baskets. +/// the defaults written in the specification; the preset supplies six of them. The file +/// is the only source of truth (5.1, decision C10): the preset is chosen in Impostazioni ▸ +/// Strategia and a saved change reaches the running engine through +/// on its decision thread. A change applies to new baskets; an open basket keeps the take +/// profit, the maximum loss, the z stop and the adds it entered with. /// public sealed class BasketStrategyConfig { @@ -295,6 +298,137 @@ public sealed class BasketStrategyConfig }; } + /// + /// Whether trades the same instruments: the same baskets, in + /// the same order, on the same pairs, and the same choice about the direct crosses. + /// These are what the engine builds its series and slots from at start; anything else + /// can change under a running engine (), these need a restart. + /// + public bool SameStructure(BasketStrategyConfig other) + { + ArgumentNullException.ThrowIfNull(other); + return PreferDirectCross == other.PreferDirectCross && SameBaskets(other); + } + + /// The same pairs in the same order (the enable switches and the notes may differ). + private bool SameBaskets(BasketStrategyConfig other) + { + if (Baskets.Count != other.Baskets.Count) + { + return false; + } + + for (int i = 0; i < Baskets.Count; i++) + { + if (!Baskets[i].A.Equals(other.Baskets[i].A, StringComparison.OrdinalIgnoreCase) || + !Baskets[i].B.Equals(other.Baskets[i].B, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + } + + return true; + } + + /// + /// Copies every value of into this instance, in place: the + /// decider, the executor and the learning state hold this very object, so they read + /// the new values at their next use. The nested sections are updated field by field + /// (a reference taken to them stays valid), and so are the baskets when the structure + /// is the same (the engine's slots hold those definitions); a different list is + /// replaced, which only a fresh engine may see. + /// + public void CopyFrom(BasketStrategyConfig source) + { + ArgumentNullException.ThrowIfNull(source); + if (ReferenceEquals(source, this)) + { + return; + } + + bool sameBaskets = SameBaskets(source); + Preset = source.Preset; + SignalMode = source.SignalMode; + ExitMode = source.ExitMode; + AveragingMode = source.AveragingMode; + TpMode = source.TpMode; + SameCrossPolicy = source.SameCrossPolicy; + PreferDirectCross = source.PreferDirectCross; + InvertSignal = source.InvertSignal; + Window = source.Window; + WindowShort = source.WindowShort; + RhoMin = source.RhoMin; + RhoShortMin = source.RhoShortMin; + HalfLifeMinBars = source.HalfLifeMinBars; + HalfLifeMaxBars = source.HalfLifeMaxBars; + HalfLifeRecalcHours = source.HalfLifeRecalcHours; + AtrPeriod = source.AtrPeriod; + EwmaSpan = source.EwmaSpan; + TrendPeriod = source.TrendPeriod; + ZOut = source.ZOut; + DIn = source.DIn; + AnchorBars = source.AnchorBars; + GridStepZ = source.GridStepZ; + LotMultiplier = source.LotMultiplier; + MaxLossPerBasketPct = source.MaxLossPerBasketPct; + RhoBreak = source.RhoBreak; + RhoBreakBars = source.RhoBreakBars; + MaxHoldingBars = source.MaxHoldingBars; + TpAtrMultiple = source.TpAtrMultiple; + CostMultiple = source.CostMultiple; + SpreadMedianMultiple = source.SpreadMedianMultiple; + SpreadAnomalyMultiple = source.SpreadAnomalyMultiple; + SlippagePipsPerLeg = source.SlippagePipsPerLeg; + OvernightPipsPerDay = source.OvernightPipsPerDay; + BlackoutBeforeMin = source.BlackoutBeforeMin; + BlackoutAfterMin = source.BlackoutAfterMin; + FridayCutoffUtcHour = source.FridayCutoffUtcHour; + OpenDelayMinutes = source.OpenDelayMinutes; + Sessions = [.. source.Sessions]; + MaxEffectiveLeverage = source.MaxEffectiveLeverage; + OrderLeverage = source.OrderLeverage; + VolScaleMin = source.VolScaleMin; + VolScaleMax = source.VolScaleMax; + VolAverageDays = source.VolAverageDays; + MlMinProbability = source.MlMinProbability; + EquityStopPct = source.EquityStopPct; + DailyLossPct = source.DailyLossPct; + LegTimeoutSec = source.LegTimeoutSec; + ClockSkewMaxSeconds = source.ClockSkewMaxSeconds; + ZInOverride = source.ZInOverride; + RiskPerBasketPctOverride = source.RiskPerBasketPctOverride; + MaxBasketsOverride = source.MaxBasketsOverride; + TpPipsOverride = source.TpPipsOverride; + MaxAddsOverride = source.MaxAddsOverride; + ZStopOverride = source.ZStopOverride; + + Risk.MaxMarginUsePct = source.Risk.MaxMarginUsePct; + Risk.MaxMarginPerBasketPct = source.Risk.MaxMarginPerBasketPct; + Risk.MarginBufferPct = source.Risk.MarginBufferPct; + Risk.CloseForeignOnKill = source.Risk.CloseForeignOnKill; + Risk.MarginCallBlockRatio = source.Risk.MarginCallBlockRatio; + Risk.MarginCallCloseRatio = source.Risk.MarginCallCloseRatio; + Recovery.ThresholdMinutes = source.Recovery.ThresholdMinutes; + Recovery.WarmupMinutes = source.Recovery.WarmupMinutes; + Recovery.HeartbeatSeconds = source.Recovery.HeartbeatSeconds; + Learning.Enabled = source.Learning.Enabled; + Learning.WeeklyCycle = source.Learning.WeeklyCycle; + Learning.Challenger = source.Learning.Challenger; + + if (sameBaskets) + { + for (int i = 0; i < Baskets.Count; i++) + { + Baskets[i].Enabled = source.Baskets[i].Enabled; + Baskets[i].Note = source.Baskets[i].Note; + } + } + else + { + Baskets = [.. source.Baskets.Select(static b => new BasketDefinition { A = b.A, B = b.B, Enabled = b.Enabled, Note = b.Note })]; + } + } + public static List DefaultBaskets() => [ new() { A = "EURUSD", B = "USDCHF", Note = "cross sintetico EURCHF" }, @@ -686,14 +820,14 @@ public sealed class BasketStrategyConfig { "_comment": "Encelado — strategia Correlation Baskets su eToro. Cinque basket di due coppie forex correlate: si entra quando il cross sintetico diverge (z-score), si esce quando converge o al take-profit di basket in pip; lo stop di basket è obbligatorio. Ogni chiave con '_' davanti è documentazione.", - "_preset": "Conservative | Moderate | Aggressive. Fissa zIn, riskPerBasketPct, maxBaskets, tpPips, maxAdds, zStop; si cambia a caldo dalla finestra senza toccare i basket aperti. Le chiavi omonime qui sotto, se presenti, sovrascrivono il preset.", + "_preset": "Conservative | Moderate | Aggressive. Fissa zIn, riskPerBasketPct, maxBaskets, tpPips, maxAdds, zStop. Si sceglie in Impostazioni ▸ Strategia e il bot lo applica subito ai basket nuovi: quelli già aperti tengono take-profit, perdita massima, zStop e aggiunte con cui sono entrati. Le chiavi omonime qui sotto, se presenti, sovrascrivono il preset.", "preset": "Moderate", "_signalMode": "ZScoreSynthetic (default, |z| >= zIn sul cross sintetico) oppure PipDivergence (fedele all'interfaccia Titany: divergenza in pip dall'ancora, dIn).", "signalMode": "ZScoreSynthetic", "_exitMode": "First = la prima fra TP in pip e rientro dello z; FixedPips = solo TP in pip lordi; ZReturn = solo |z| <= zOut.", "exitMode": "First", - "_averagingMode": "Off | AddOnce | Grid. Off in live; AddOnce in paper. Moltiplicatore di lotto sempre 1,0 (niente martingala).", + "_averagingMode": "Off | AddOnce | Grid. Off di fabbrica; AddOnce ammette una sola aggiunta per basket, Grid fino a maxAdds. Moltiplicatore di lotto sempre 1,0 (niente martingala).", "averagingMode": "Off", "tpMode": "Pips", "_sameCrossPolicy": "I basket 4 e 5 sono entrambi EURCAD: Exclusive = uno solo aperto per volta; Half = entrambi a metà size.", diff --git a/Encelado/src/Encelado.Core/Baskets/ExecutionMode.cs b/Encelado/src/Encelado.Core/Baskets/ExecutionMode.cs index 666da48..51a2424 100644 --- a/Encelado/src/Encelado.Core/Baskets/ExecutionMode.cs +++ b/Encelado/src/Encelado.Core/Baskets/ExecutionMode.cs @@ -1,17 +1,24 @@ namespace Encelado.Core.Baskets; /// -/// Who fills the orders. The bot runs unattended in every mode: it opens and closes -/// baskets by itself. The default is : real orders on eToro's demo -/// account, virtual money. needs the configuration flag and the typed -/// phrase at start (decision D-20, 2026-09-16: no manual approval of single orders). +/// Who fills the orders, and on which eToro account. The bot runs unattended in both +/// modes: it opens and closes baskets by itself. The default is : real +/// orders on eToro's demo account, virtual money. is the real account +/// and needs the configuration flag and the phrase typed in the interface at every start +/// (decision D-20, 2026-09-16: no manual approval of single orders). The mode also picks +/// the account: there is no separate environment setting (5.1, decision C6), so a demo +/// mode can never send orders to the real account. +/// +/// The explicit values keep the numbers of the previous versions (Paper was 1 and is +/// gone: the eToro demo account is the simulator). Nothing stores the number; the +/// ledger, the state and the heartbeat store the name. +/// /// public enum ExecutionMode { Backtest = 0, - Paper, - Demo, - Live, + Demo = 2, + Live = 3, } public static class ExecutionModeExtensions @@ -22,33 +29,51 @@ public static class ExecutionModeExtensions public static bool UsesVenue(this ExecutionMode m) => m is ExecutionMode.Demo or ExecutionMode.Live; - /// The label shown in the badge: PAPER, DEMO, LIVE or BACKTEST. + /// The label shown in the badge: DEMO, LIVE or BACKTEST. public static string Badge(this ExecutionMode m) => m switch { - ExecutionMode.Paper => "PAPER", ExecutionMode.Demo => "DEMO", ExecutionMode.Live => "LIVE", _ => "BACKTEST", }; - /// paper, demo, live or backtest, for the badge colour. + /// demo, live or backtest, for the badge colour. public static string Kind(this ExecutionMode m) => m.Badge().ToLowerInvariant(); - /// Whether is a mode name of a previous version (the approve/auto pairs), which still parse. - public static bool IsLegacyName(string? text) => Normalise(text) is "demoapprove" or "demoauto" or "liveapprove" or "liveauto"; + /// The eToro account a mode trades on: demo or live (the API's words). + public static string Account(this ExecutionMode m) => m.IsLive() ? "live" : "demo"; + + /// + /// Whether is a mode name of a previous version, which still + /// parses: the approve/auto pairs of 4.0 and Paper, read as Demo since 5.1. + /// + public static bool IsLegacyName(string? text) => Normalise(text) is "demoapprove" or "demoauto" or "liveapprove" or "liveauto" or "paper"; public static bool TryParse(string? text, out ExecutionMode mode) { switch (Normalise(text)) { case "backtest": mode = ExecutionMode.Backtest; return true; - case "paper": mode = ExecutionMode.Paper; return true; - case "demo" or "demoapprove" or "demoauto": mode = ExecutionMode.Demo; return true; + case "demo" or "demoapprove" or "demoauto" or "paper": mode = ExecutionMode.Demo; return true; case "live" or "real" or "liveapprove" or "liveauto": mode = ExecutionMode.Live; return true; default: mode = ExecutionMode.Demo; return false; } } + /// + /// The merge rule of 5.1 for files and containers of 5.0, where mode and account were + /// two settings: the result is Live only when the mode said Live and the account + /// said real; every other combination is Demo. Demo + real (orders to the real account + /// without the Live gate) and Live + demo both become Demo. + /// is true when the two inputs did not say the same thing. + /// + public static ExecutionMode Merge(ExecutionMode mode, string? environment, out bool disagree) + { + bool real = (environment ?? "demo").Trim().Equals("real", StringComparison.OrdinalIgnoreCase); + disagree = mode.IsLive() != real; + return mode.IsLive() && real ? ExecutionMode.Live : ExecutionMode.Demo; + } + private static string Normalise(string? text) => (text ?? string.Empty).Trim().Replace("-", string.Empty, StringComparison.Ordinal).Replace("_", string.Empty, StringComparison.Ordinal).ToLowerInvariant(); } diff --git a/Encelado/src/Encelado.Core/Baskets/Learning/ThompsonBandit.cs b/Encelado/src/Encelado.Core/Baskets/Learning/ThompsonBandit.cs index 6ceab79..18d3c29 100644 --- a/Encelado/src/Encelado.Core/Baskets/Learning/ThompsonBandit.cs +++ b/Encelado/src/Encelado.Core/Baskets/Learning/ThompsonBandit.cs @@ -6,8 +6,9 @@ namespace Encelado.Core.Baskets.Learning; /// /// Level 3 (§8.6): Thompson sampling with Beta posteriors, one arm per (preset × /// volatility tercile). Reward 1 when a basket closes with a net profit, 0 otherwise. -/// It proposes; the engine applies the proposal only in paper/demo, and never in live -/// until the forward test says so. Exploration is capped at 10 % of the choices. +/// It proposes and never applies (since 5.0): the preset is the operator's choice in the +/// settings, and a proposal goes through the forward test. Exploration is capped at 10 % +/// of the choices. /// /// Why a bandit and not deep RL: with a few hundred episodes a year, three arms per /// context and a binary reward are what the data can tell apart; a value network would diff --git a/Encelado/src/Encelado.Core/Baskets/PendingEntry.cs b/Encelado/src/Encelado.Core/Baskets/PendingEntry.cs index 77e4957..01ed5b6 100644 --- a/Encelado/src/Encelado.Core/Baskets/PendingEntry.cs +++ b/Encelado/src/Encelado.Core/Baskets/PendingEntry.cs @@ -25,6 +25,12 @@ public sealed class PendingEntry public required double MaxLossUsd { get; init; } + /// The z stop of the preset at decision time (NaN in a plan saved before 5.1). + public double ZStop { get; init; } = double.NaN; + + /// The adds allowed by the preset at decision time (−1 in a plan saved before 5.1). + public int MaxAdds { get; init; } = -1; + public double EntryCostPips { get; init; } = double.NaN; public required double EquityAtEntry { get; init; } @@ -56,6 +62,12 @@ public sealed class PendingEntry w.WriteNumber("unitsB", UnitsB); w.WriteNumber("tpPips", TpPips); w.WriteNumber("maxLossUsd", MaxLossUsd); + if (double.IsFinite(ZStop)) + { + w.WriteNumber("zStop", ZStop); + } + + w.WriteNumber("maxAdds", MaxAdds); w.WriteNumber("entryCostPips", double.IsFinite(EntryCostPips) ? EntryCostPips : 0); w.WriteNumber("equityAtEntry", EquityAtEntry); w.WriteString("motivazione", Motivazione); @@ -83,6 +95,8 @@ public sealed class PendingEntry UnitsB = e.GetProperty("unitsB").GetDouble(), TpPips = e.GetProperty("tpPips").GetDouble(), MaxLossUsd = e.GetProperty("maxLossUsd").GetDouble(), + ZStop = e.TryGetProperty("zStop", out JsonElement zs) && zs.ValueKind == JsonValueKind.Number ? zs.GetDouble() : double.NaN, + MaxAdds = e.TryGetProperty("maxAdds", out JsonElement ma) && ma.ValueKind == JsonValueKind.Number ? ma.GetInt32() : -1, EntryCostPips = e.GetProperty("entryCostPips").GetDouble(), EquityAtEntry = e.GetProperty("equityAtEntry").GetDouble(), Motivazione = e.GetProperty("motivazione").GetString() ?? string.Empty, diff --git a/Encelado/src/Encelado.Core/Broker/Broker.cs b/Encelado/src/Encelado.Core/Broker/Broker.cs index e29a84f..889b587 100644 --- a/Encelado/src/Encelado.Core/Broker/Broker.cs +++ b/Encelado/src/Encelado.Core/Broker/Broker.cs @@ -2,13 +2,12 @@ using Encelado.Core.Baskets.Data; namespace Encelado.Core.Broker; -/// Where the orders go. Shown in the window at all times, in colour. +/// Where the orders go. Shown in the interface at all times, in colour. The values keep the numbers of 5.0 (Paper, 1, is gone). public enum BrokerEnvironment { Backtest = 0, - Paper, - Demo, - Real, + Demo = 2, + Real = 3, } /// @@ -190,9 +189,8 @@ public sealed record ClosedTrade( } /// -/// Everything the engine asks of a venue. Three implementations: the real eToro API, -/// the paper simulator (real quotes, local fills) and the backtest replay. The engine -/// never knows which one it holds. +/// Everything the engine asks of a venue. Two implementations: the real eToro API (demo +/// or real account) and the backtest replay. The engine never knows which one it holds. /// public interface IBroker : IAsyncDisposable { diff --git a/Encelado/src/Encelado.Core/Broker/PaperBroker.cs b/Encelado/src/Encelado.Core/Broker/PaperBroker.cs deleted file mode 100644 index b1eb9ce..0000000 --- a/Encelado/src/Encelado.Core/Broker/PaperBroker.cs +++ /dev/null @@ -1,560 +0,0 @@ -using System.Globalization; -using System.Text; -using System.Text.Json; -using Encelado.Core.Baskets; -using Encelado.Core.Baskets.Data; - -namespace Encelado.Core.Broker; - -/// Knobs of the local simulator. -public sealed class PaperBrokerOptions -{ - public double StartingBalance { get; set; } = 10_000; - - /// Slippage charged on every fill, in pips per leg, on top of the real spread. - public double SlippagePips { get; set; } = 0.3; - - /// Overnight fee per leg per calendar day, in pips, charged at 21:00 UTC. Weekend counts three days. - public double OvernightPipsPerDay { get; set; } = 0.3; - - /// Where the simulator keeps its positions between runs. Empty = memory only. - public string StatePath { get; set; } = string.Empty; -} - -/// -/// The paper venue: quotes, instruments, candles and cost estimates come from a real -/// broker in read-only use; fills, positions, stops and the account are simulated here, -/// at the real bid/ask of the moment plus a configured slippage. -/// -/// Stops and take-profits are evaluated on every quote refresh, which is the same -/// granularity the live engine sees (a poll every few seconds), so a paper session and -/// a demo session differ only in who fills the order. -/// -/// -public sealed class PaperBroker : IBroker -{ - private readonly IBroker _feed; - private readonly PaperBrokerOptions _options; - private readonly Lock _gate = new(); - private readonly Dictionary _positions = []; - private readonly Dictionary _instruments = []; - private readonly Dictionary _quotes = []; - private readonly Dictionary _orders = new(StringComparer.OrdinalIgnoreCase); - private readonly List _closed = []; - private double _balance; - private long _nextId = 1; - private DateTime _lastOvernightUtc = DateTime.MinValue; - - private sealed class PaperPosition - { - public long Id; - public long InstrumentId; - public string Symbol = string.Empty; - public bool IsBuy; - public double Units; - public double OpenRate; - public DateTime OpenedUtc; - public double StopLoss; - public double TakeProfit; - public int Leverage; - public double Fees; - public string ClientRef = string.Empty; - } - - public PaperBroker(IBroker feed, PaperBrokerOptions options) - { - ArgumentNullException.ThrowIfNull(feed); - ArgumentNullException.ThrowIfNull(options); - _feed = feed; - _options = options; - _balance = options.StartingBalance; - Load(); - } - - public BrokerEnvironment Environment => BrokerEnvironment.Paper; - - public string Name => $"paper su {_feed.Name}"; - - public bool SupportsTrading => true; - - public TimeSpan ClockSkew => _feed.ClockSkew; - - /// Raised when the simulator closes a position on its own (stop or take-profit hit). - public event Action? PositionClosedByStop; - - // ----------------------------------------------------------------------- - // Read-only pass-through - // ----------------------------------------------------------------------- - - public async Task> GetInstrumentsAsync(IReadOnlyList symbols, CancellationToken ct) - { - IReadOnlyList list = await _feed.GetInstrumentsAsync(symbols, ct).ConfigureAwait(false); - lock (_gate) - { - foreach (Instrument i in list) - { - _instruments[i.Id] = i; - } - } - - return list; - } - - public async Task> GetQuotesAsync(IReadOnlyList instrumentIds, CancellationToken ct) - { - IReadOnlyList quotes = await _feed.GetQuotesAsync(instrumentIds, ct).ConfigureAwait(false); - MarkToMarket(quotes); - return quotes; - } - - public Task> GetCandlesAsync(long instrumentId, TimeSpan interval, int count, CancellationToken ct) => - _feed.GetCandlesAsync(instrumentId, interval, count, ct); - - public Task GetCostAsync(OrderRequest request, CancellationToken ct) => _feed.GetCostAsync(request, ct); - - // ----------------------------------------------------------------------- - // Simulation - // ----------------------------------------------------------------------- - - /// Feeds fresh quotes to the simulator: updates P&L and triggers stops. Called by too. - public void MarkToMarket(IReadOnlyList quotes) - { - ArgumentNullException.ThrowIfNull(quotes); - List<(long Id, string Reason)> hit = []; - lock (_gate) - { - foreach (QuoteSnapshot q in quotes) - { - if (q.IsValid) - { - _quotes[q.InstrumentId] = q; - } - } - - ChargeOvernight(DateTime.UtcNow); - - foreach (PaperPosition p in _positions.Values) - { - if (!_quotes.TryGetValue(p.InstrumentId, out QuoteSnapshot q) || !q.IsValid) - { - continue; - } - - double exit = p.IsBuy ? q.Bid : q.Ask; - if (p.StopLoss > 0 && (p.IsBuy ? exit <= p.StopLoss : exit >= p.StopLoss)) - { - hit.Add((p.Id, "stop nativo")); - } - else if (p.TakeProfit > 0 && (p.IsBuy ? exit >= p.TakeProfit : exit <= p.TakeProfit)) - { - hit.Add((p.Id, "take-profit nativo")); - } - } - } - - foreach ((long id, string reason) in hit) - { - CloseInternal(id, reason); - PositionClosedByStop?.Invoke(id, reason); - } - } - - public Task GetAccountAsync(CancellationToken ct) - { - lock (_gate) - { - double unrealized = 0; - double margin = 0; - foreach (PaperPosition p in _positions.Values) - { - unrealized += UnrealizedUsd(p); - margin += MarginUsd(p); - } - - double equity = _balance + unrealized; - return Task.FromResult(new AccountSnapshot(DateTime.UtcNow, "USD", _balance, equity, Math.Max(0, equity - margin), margin, unrealized)); - } - } - - public Task> GetPositionsAsync(CancellationToken ct) - { - lock (_gate) - { - List list = new(_positions.Count); - foreach (PaperPosition p in _positions.Values) - { - double current = _quotes.TryGetValue(p.InstrumentId, out QuoteSnapshot q) && q.IsValid ? (p.IsBuy ? q.Bid : q.Ask) : p.OpenRate; - list.Add(new BrokerPosition(p.Id, p.InstrumentId, p.IsBuy, p.Units, p.OpenRate, p.OpenedUtc, p.StopLoss, p.TakeProfit, p.Leverage, MarginUsd(p), UnrealizedUsd(p), p.Fees, current)); - } - - return Task.FromResult>(list); - } - } - - public Task OpenAsync(OrderRequest request, CancellationToken ct) - { - ArgumentNullException.ThrowIfNull(request); - lock (_gate) - { - if (_orders.TryGetValue(request.ClientRef, out OrderOutcome? already)) - { - return Task.FromResult(already); - } - - if (!_instruments.TryGetValue(request.InstrumentId, out Instrument? instrument)) - { - return Task.FromResult(Reject(request, "strumento sconosciuto al simulatore: chiama GetInstrumentsAsync prima")); - } - - if (!_quotes.TryGetValue(request.InstrumentId, out QuoteSnapshot q) || !q.IsValid) - { - return Task.FromResult(Reject(request, "nessuna quotazione valida per lo strumento")); - } - - if (request.Units <= 0 || request.Units < instrument.MinUnits) - { - return Task.FromResult(Reject(request, $"unità {request.Units} sotto il minimo {instrument.MinUnits}")); - } - - if (instrument.MaxUnitsPerOrder > 0 && request.Units > instrument.MaxUnitsPerOrder) - { - return Task.FromResult(Reject(request, $"unità {request.Units} sopra il massimo per ordine {instrument.MaxUnitsPerOrder}")); - } - - if (!request.IsBuy && request.StopLossRate is null) - { - return Task.FromResult(Reject(request, "eToro richiede uno stop per le vendite allo scoperto")); - } - - double slip = _options.SlippagePips * instrument.Pip; - double fill = instrument.RoundPrice(request.IsBuy ? q.Ask + slip : q.Bid - slip); - - double? mid(string s) => MidOf(s); - double notional = PipMath.NotionalUsd(instrument.Symbol, request.Units, fill, mid); - if (double.IsNaN(notional)) - { - return Task.FromResult(Reject(request, "impossibile convertire il nozionale in USD: manca la coppia di conversione")); - } - - if (notional < instrument.MinExposure) - { - return Task.FromResult(Reject(request, string.Create(CultureInfo.InvariantCulture, $"esposizione {notional:F0} USD sotto il minimo {instrument.MinExposure:F0}"))); - } - - double margin = notional / Math.Max(1, request.Leverage); - double available = AvailableLocked(); - if (margin > available) - { - return Task.FromResult(Reject(request, string.Create(CultureInfo.InvariantCulture, $"margine richiesto {margin:F2} USD oltre il disponibile {available:F2}"))); - } - - PaperPosition p = new() - { - Id = _nextId++, - InstrumentId = request.InstrumentId, - Symbol = instrument.Symbol, - IsBuy = request.IsBuy, - Units = request.Units, - OpenRate = fill, - OpenedUtc = DateTime.UtcNow, - StopLoss = request.StopLossRate ?? 0, - TakeProfit = request.TakeProfitRate ?? 0, - Leverage = Math.Max(1, request.Leverage), - ClientRef = request.ClientRef, - }; - _positions[p.Id] = p; - - OrderOutcome outcome = new(true, false, p.Id, p.Id, fill, request.Units, p.OpenedUtc, 0, "Filled", string.Empty); - _orders[request.ClientRef] = outcome; - Save(); - return Task.FromResult(outcome); - } - } - - public Task LookupOrderAsync(string clientRef, CancellationToken ct) - { - lock (_gate) - { - return Task.FromResult(_orders.TryGetValue(clientRef, out OrderOutcome? o) ? o : null); - } - } - - public Task LookupOrderByIdAsync(long orderId, CancellationToken ct) - { - lock (_gate) - { - return Task.FromResult(_orders.Values.FirstOrDefault(o => o.OrderId == orderId)); - } - } - - /// The simulator fills at once: there is never an order to cancel. - public Task CancelOrderAsync(long orderId, CancellationToken ct) => Task.FromResult(false); - - public Task CloseAsync(long positionId, long instrumentId, CancellationToken ct) - { - CloseOutcome? outcome = CloseInternal(positionId, "chiusura richiesta"); - return Task.FromResult(outcome ?? new CloseOutcome(false, true, 0, 0, 0, DateTime.UtcNow, 0, $"posizione {positionId} non trovata")); - } - - public Task UpdateStopsAsync(long positionId, double? stopLoss, double? takeProfit, CancellationToken ct) - { - lock (_gate) - { - if (!_positions.TryGetValue(positionId, out PaperPosition? p)) - { - return Task.FromResult(false); - } - - if (stopLoss is { } sl) - { - p.StopLoss = sl; - } - - if (takeProfit is { } tp) - { - p.TakeProfit = tp; - } - - Save(); - return Task.FromResult(true); - } - } - - public Task> GetClosedTradesAsync(DateTime fromUtc, CancellationToken ct) - { - lock (_gate) - { - return Task.FromResult>([.. _closed.Where(c => c.ClosedUtc >= fromUtc)]); - } - } - - private CloseOutcome? CloseInternal(long positionId, string reason) - { - lock (_gate) - { - if (!_positions.Remove(positionId, out PaperPosition? p)) - { - return null; - } - - if (!_quotes.TryGetValue(p.InstrumentId, out QuoteSnapshot q) || !q.IsValid) - { - _positions[positionId] = p; - return new CloseOutcome(false, true, 0, 0, 0, DateTime.UtcNow, 0, "nessuna quotazione valida per chiudere"); - } - - Instrument instrument = _instruments[p.InstrumentId]; - double slip = _options.SlippagePips * instrument.Pip; - double exit = instrument.RoundPrice(p.IsBuy ? q.Bid - slip : q.Ask + slip); - double pnl = PipMath.LegPnlUsd(p.Symbol, p.IsBuy, p.Units, p.OpenRate, exit, MidOf); - if (double.IsNaN(pnl)) - { - pnl = 0; - } - - pnl -= p.Fees; - _balance += pnl; - DateTime now = DateTime.UtcNow; - _closed.Add(new ClosedTrade(p.Id, p.InstrumentId, p.IsBuy, p.Units, p.OpenRate, exit, p.OpenedUtc, now, pnl, p.Fees)); - Save(); - return new CloseOutcome(true, false, _nextId++, exit, p.Units, now, pnl, reason); - } - } - - private OrderOutcome Reject(OrderRequest request, string why) - { - OrderOutcome o = new(false, true, 0, 0, 0, request.Units, DateTime.UtcNow, 0, "Rejected", why); - _orders[request.ClientRef] = o; - return o; - } - - private double AvailableLocked() - { - double unrealized = 0; - double margin = 0; - foreach (PaperPosition p in _positions.Values) - { - unrealized += UnrealizedUsd(p); - margin += MarginUsd(p); - } - - return Math.Max(0, _balance + unrealized - margin); - } - - private double UnrealizedUsd(PaperPosition p) - { - if (!_quotes.TryGetValue(p.InstrumentId, out QuoteSnapshot q) || !q.IsValid) - { - return -p.Fees; - } - - double exit = p.IsBuy ? q.Bid : q.Ask; - double pnl = PipMath.LegPnlUsd(p.Symbol, p.IsBuy, p.Units, p.OpenRate, exit, MidOf); - return (double.IsNaN(pnl) ? 0 : pnl) - p.Fees; - } - - private double MarginUsd(PaperPosition p) - { - double notional = PipMath.NotionalUsd(p.Symbol, p.Units, p.OpenRate, MidOf); - return (double.IsNaN(notional) ? 0 : notional) / Math.Max(1, p.Leverage); - } - - private double? MidOf(string symbol) - { - foreach ((long id, Instrument i) in _instruments) - { - if (i.Symbol.Equals(symbol, StringComparison.OrdinalIgnoreCase) && _quotes.TryGetValue(id, out QuoteSnapshot q) && q.IsValid) - { - return q.Mid; - } - } - - return null; - } - - /// Overnight fee once per calendar day at 21:00 UTC; Friday counts for three nights. - private void ChargeOvernight(DateTime now) - { - DateTime today21 = new(now.Year, now.Month, now.Day, 21, 0, 0, DateTimeKind.Utc); - if (now < today21 || _lastOvernightUtc >= today21 || _positions.Count == 0) - { - return; - } - - int nights = now.DayOfWeek == DayOfWeek.Friday ? 3 : 1; - foreach (PaperPosition p in _positions.Values) - { - if (p.OpenedUtc >= today21) - { - continue; - } - - double pipUsd = PipMath.PipValueUsd(p.Symbol, p.Units, MidOf); - if (!double.IsNaN(pipUsd)) - { - p.Fees += _options.OvernightPipsPerDay * nights * pipUsd; - } - } - - _lastOvernightUtc = today21; - Save(); - } - - // ----------------------------------------------------------------------- - // Persistence (JSON, atomic) - // ----------------------------------------------------------------------- - - private void Save() - { - if (string.IsNullOrWhiteSpace(_options.StatePath)) - { - return; - } - - try - { - string full = Path.GetFullPath(_options.StatePath); - Directory.CreateDirectory(Path.GetDirectoryName(full)!); - using MemoryStream ms = new(); - using (Utf8JsonWriter w = new(ms, new JsonWriterOptions { Indented = true })) - { - w.WriteStartObject(); - w.WriteNumber("balance", _balance); - w.WriteNumber("nextId", _nextId); - w.WriteString("lastOvernightUtc", _lastOvernightUtc.ToString("O", CultureInfo.InvariantCulture)); - w.WriteStartArray("positions"); - foreach (PaperPosition p in _positions.Values) - { - w.WriteStartObject(); - w.WriteNumber("id", p.Id); - w.WriteNumber("instrumentId", p.InstrumentId); - w.WriteString("symbol", p.Symbol); - w.WriteBoolean("isBuy", p.IsBuy); - w.WriteNumber("units", p.Units); - w.WriteNumber("openRate", p.OpenRate); - w.WriteString("openedUtc", p.OpenedUtc.ToString("O", CultureInfo.InvariantCulture)); - w.WriteNumber("stopLoss", p.StopLoss); - w.WriteNumber("takeProfit", p.TakeProfit); - w.WriteNumber("leverage", p.Leverage); - w.WriteNumber("fees", p.Fees); - w.WriteString("clientRef", p.ClientRef); - w.WriteEndObject(); - } - - w.WriteEndArray(); - w.WriteEndObject(); - } - - File.WriteAllBytes(full + ".tmp", ms.ToArray()); - File.Move(full + ".tmp", full, overwrite: true); - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) - { - // The simulator keeps working in memory; the engine logs the account state anyway. - } - } - - private void Load() - { - if (string.IsNullOrWhiteSpace(_options.StatePath) || !File.Exists(_options.StatePath)) - { - return; - } - - try - { - using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(_options.StatePath)); - JsonElement root = doc.RootElement; - _balance = root.TryGetProperty("balance", out JsonElement b) ? b.GetDouble() : _balance; - _nextId = root.TryGetProperty("nextId", out JsonElement n) ? n.GetInt64() : 1; - if (root.TryGetProperty("lastOvernightUtc", out JsonElement lo) && - DateTime.TryParse(lo.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t)) - { - _lastOvernightUtc = t; - } - - if (root.TryGetProperty("positions", out JsonElement arr)) - { - foreach (JsonElement e in arr.EnumerateArray()) - { - PaperPosition p = new() - { - Id = e.GetProperty("id").GetInt64(), - InstrumentId = e.GetProperty("instrumentId").GetInt64(), - Symbol = e.GetProperty("symbol").GetString() ?? string.Empty, - IsBuy = e.GetProperty("isBuy").GetBoolean(), - Units = e.GetProperty("units").GetDouble(), - OpenRate = e.GetProperty("openRate").GetDouble(), - OpenedUtc = DateTime.Parse(e.GetProperty("openedUtc").GetString()!, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal), - StopLoss = e.GetProperty("stopLoss").GetDouble(), - TakeProfit = e.GetProperty("takeProfit").GetDouble(), - Leverage = e.GetProperty("leverage").GetInt32(), - Fees = e.GetProperty("fees").GetDouble(), - ClientRef = e.TryGetProperty("clientRef", out JsonElement cr) ? cr.GetString() ?? string.Empty : string.Empty, - }; - _positions[p.Id] = p; - } - } - } - catch (Exception ex) when (ex is IOException or JsonException or KeyNotFoundException or InvalidOperationException) - { - // A corrupt state file starts the simulator fresh rather than crashing the bot. - } - } - - public string Describe() - { - lock (_gate) - { - StringBuilder sb = new(); - sb.Append(CultureInfo.InvariantCulture, $"paper: saldo {_balance:F2} USD, {_positions.Count} posizioni"); - return sb.ToString(); - } - } - - public ValueTask DisposeAsync() - { - Save(); - return ValueTask.CompletedTask; - } -} diff --git a/Encelado/src/Encelado.Core/Notifications/INotifier.cs b/Encelado/src/Encelado.Core/Notifications/INotifier.cs index f86a34b..47c5b22 100644 --- a/Encelado/src/Encelado.Core/Notifications/INotifier.cs +++ b/Encelado/src/Encelado.Core/Notifications/INotifier.cs @@ -26,6 +26,13 @@ public interface INotifier /// One line for the dashboard: last delivery, queue length, last error. string Status { get; } + /// + /// Whether a message queued now would be delivered somewhere. The engine skips the + /// work of composing the scheduled messages (hourly status, daily summary) when it + /// is false; it can change at any moment, when the channel is switched on or off. + /// + bool IsActive { get; } + /// Queues a message. Returns at once; delivery is the channel's business. void Notify(NotificationKind kind, string title, string text); } @@ -37,6 +44,8 @@ public sealed class NullNotifier : INotifier public string Status => "notifiche non configurate"; + public bool IsActive => false; + public void Notify(NotificationKind kind, string title, string text) { // Nothing to deliver to. diff --git a/Encelado/src/Encelado.Core/Notifications/NotifierHub.cs b/Encelado/src/Encelado.Core/Notifications/NotifierHub.cs new file mode 100644 index 0000000..3d3f705 --- /dev/null +++ b/Encelado/src/Encelado.Core/Notifications/NotifierHub.cs @@ -0,0 +1,183 @@ +using System.Globalization; + +namespace Encelado.Core.Notifications; + +/// +/// The one notifier the engine and the host hold for the whole process, whatever the +/// settings say from one minute to the next (5.1, hot apply). Behind it sits either +/// nothing () or a , swapped by +/// after every change of the Telegram settings or of the +/// token: switched on, switched off, a new token (a new channel), commands started or +/// stopped. The token never sits in the shared configuration: the hub reads it from +/// token (the encrypted store) and hands it only to the channel's private copy of +/// the options. +/// +public sealed class NotifierHub : INotifier, IAsyncDisposable +{ + private readonly TelegramOptions _shared; + private readonly Func _token; + private readonly Action _log; + private readonly Func _factory; + private readonly SemaphoreSlim _gate = new(1, 1); + private volatile INotifier _inner = NullNotifier.Instance; + private TelegramNotifier? _telegram; + private TelegramOptions? _options; + private string _tokenInUse = string.Empty; + private Func>? _commandHandler; + + /// The configuration's Telegram section: read at every reconfiguration, never written. + /// The bot token from the secret store; empty when none is saved. + /// Where the hub says what it switched. + /// Builds the channel (the tests pass a fake transport). + public NotifierHub(TelegramOptions shared, Func token, Action? log = null, Func? factory = null) + { + _shared = shared ?? throw new ArgumentNullException(nameof(shared)); + _token = token ?? throw new ArgumentNullException(nameof(token)); + _log = log ?? (static _ => { }); + _factory = factory ?? (o => new TelegramNotifier(o, null, _log)); + } + + /// Answers a command from the authorised chat; handed to every channel the hub builds. + public Func>? CommandHandler + { + get => _commandHandler; + set + { + _commandHandler = value; + if (_telegram is { } t) + { + t.CommandHandler = value; + } + } + } + + /// The live Telegram channel, or null when Telegram is off (for the diagnostics page). + public TelegramNotifier? Telegram => _telegram; + + public bool IsActive => _inner.IsActive; + + public string Status + { + get + { + if (_telegram is { } t) + { + return t.Status; + } + + return _shared.Enabled + ? "Telegram attivo nelle impostazioni ma senza token o chat id: nessun messaggio parte" + : NullNotifier.Instance.Status; + } + } + + public void Notify(NotificationKind kind, string title, string text) => _inner.Notify(kind, title, text); + + /// + /// Brings the channel in line with the settings and the stored token: builds, replaces + /// or drops the Telegram channel, and starts or stops its command poller. Cheap when + /// nothing changed; safe to call from any thread. + /// + public async Task ReconfigureAsync() + { + await _gate.WaitAsync().ConfigureAwait(false); + try + { + string token = (_token() ?? string.Empty).Trim(); + TelegramOptions wanted = new() { BotToken = token }; + wanted.CopySettingsFrom(_shared); + + if (!wanted.IsUsable) + { + if (_telegram is { } old) + { + _inner = NullNotifier.Instance; + _telegram = null; + _options = null; + _tokenInUse = string.Empty; + await old.DisposeAsync().ConfigureAwait(false); + _log(wanted.Enabled ? "Telegram spento: manca il token o il chat id" : "Telegram spento dalle impostazioni"); + } + else if (wanted.Enabled) + { + _log("Telegram attivo nelle impostazioni ma senza token o chat id: notifiche disattivate"); + } + + return; + } + + if (_telegram is { } current && !token.Equals(_tokenInUse, StringComparison.Ordinal)) + { + // A new token is a new bot: a new channel, the old one drained and closed. + _inner = NullNotifier.Instance; + _telegram = null; + _options = null; + await current.DisposeAsync().ConfigureAwait(false); + } + + if (_telegram is null) + { + _options = wanted; + TelegramNotifier created = _factory(_options); + created.CommandHandler = _commandHandler; + _telegram = created; + _tokenInUse = token; + _inner = created; + _log(string.Create(CultureInfo.InvariantCulture, $"Telegram attivo: chat {wanted.ChatId}, stato orario {(wanted.HourlyStatus ? "sì" : "no")}, eventi {(wanted.EventAlerts ? "sì" : "no")}, riepilogo alle {wanted.DailySummaryUtcHour:00}:00 UTC, comandi {(wanted.Commands ? "sì" : "no")}")); + } + else + { + // Same bot: the channel reads its options live, so a new chat id or switch applies at once. + _options!.CopySettingsFrom(_shared); + } + + if (_options!.Commands) + { + _telegram.StartCommands(); + } + else if (_telegram.CommandsRunning) + { + await _telegram.StopCommandsAsync().ConfigureAwait(false); + _log("Telegram: comandi dalla chat spenti"); + } + } + finally + { + _gate.Release(); + } + } + + /// One test message to the configured chat, delivered now (not queued): the settings page shows the outcome. + public async Task<(bool Ok, string Message)> SendTestAsync(CancellationToken ct) + { + TelegramNotifier? t = _telegram; + if (t is null) + { + return (false, _shared.Enabled ? "Telegram non è pronto: manca il token o il chat id" : "Telegram è spento nelle impostazioni"); + } + + string text = TelegramNotifier.Compose(NotificationKind.Event, "Messaggio di prova", string.Create(CultureInfo.InvariantCulture, $"Encelado ti scrive dalla pagina Impostazioni ({DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC).")); + bool ok = await t.DeliverAsync(text, ct).ConfigureAwait(false); + return ok ? (true, "messaggio di prova consegnato") : (false, $"messaggio di prova non consegnato: {t.LastError}"); + } + + public async ValueTask DisposeAsync() + { + await _gate.WaitAsync().ConfigureAwait(false); + try + { + _inner = NullNotifier.Instance; + if (_telegram is { } t) + { + _telegram = null; + await t.DisposeAsync().ConfigureAwait(false); + } + } + finally + { + _gate.Release(); + } + + _gate.Dispose(); + } +} diff --git a/Encelado/src/Encelado.Core/Notifications/TelegramNotifier.cs b/Encelado/src/Encelado.Core/Notifications/TelegramNotifier.cs index a4fa4ed..f909a91 100644 --- a/Encelado/src/Encelado.Core/Notifications/TelegramNotifier.cs +++ b/Encelado/src/Encelado.Core/Notifications/TelegramNotifier.cs @@ -11,10 +11,14 @@ public sealed class TelegramOptions { public bool Enabled { get; set; } - /// From TELEGRAM_BOT_TOKEN; never in a file of the repository. + /// + /// The bot's token. Never in a file and never in the shared configuration: it lives + /// encrypted in the secret store, and only the private copy handed to the channel + /// carries it (see ). + /// public string BotToken { get; set; } = string.Empty; - /// The one chat the bot talks to and listens to (TELEGRAM_CHAT_ID or notifications.telegram.chatId). + /// The one chat the bot talks to and listens to (notifications.telegram.chatId). public string ChatId { get; set; } = string.Empty; public bool HourlyStatus { get; set; } = true; @@ -30,6 +34,19 @@ public sealed class TelegramOptions public string BaseUrl { get; set; } = "https://api.telegram.org"; public bool IsUsable => Enabled && BotToken.Length > 0 && ChatId.Length > 0; + + /// Copies every field but the token (which the caller decides) from . + public void CopySettingsFrom(TelegramOptions source) + { + ArgumentNullException.ThrowIfNull(source); + Enabled = source.Enabled; + ChatId = source.ChatId; + HourlyStatus = source.HourlyStatus; + EventAlerts = source.EventAlerts; + DailySummaryUtcHour = source.DailySummaryUtcHour; + Commands = source.Commands; + BaseUrl = source.BaseUrl; + } } /// @@ -49,7 +66,9 @@ public sealed class TelegramNotifier : INotifier, IAsyncDisposable private readonly Channel<(NotificationKind Kind, string Title, string Text)> _queue = Channel.CreateBounded<(NotificationKind, string, string)>(new BoundedChannelOptions(500) { FullMode = BoundedChannelFullMode.DropOldest }); private readonly CancellationTokenSource _cts = new(); private readonly Task _sender; + private readonly Lock _pollGate = new(); private Task? _poller; + private CancellationTokenSource? _pollCts; private DateTime _lastSentUtc = DateTime.MinValue; private DateTime? _lastDeliveredUtc; private string _lastError = string.Empty; @@ -85,6 +104,26 @@ public sealed class TelegramNotifier : INotifier, IAsyncDisposable public int Failed => _failed; + /// When Telegram last accepted a message; null before the first. + public DateTime? LastDeliveredUtc => _lastDeliveredUtc; + + /// The last error Telegram or the network gave, or empty after a success. + public string LastError => _lastError; + + /// Whether the long-polling task for the commands is running. + public bool CommandsRunning + { + get + { + lock (_pollGate) + { + return _poller is { IsCompleted: false }; + } + } + } + + public bool IsActive => _options.IsUsable; + public string Status { get @@ -119,15 +158,92 @@ public sealed class TelegramNotifier : INotifier, IAsyncDisposable _queue.Writer.TryWrite((kind, title ?? string.Empty, text ?? string.Empty)); } - /// Starts the single long-polling task, when commands are enabled. + /// Starts the single long-polling task, when commands are enabled and it is not running already. public void StartCommands() { - if (_options.IsUsable && _options.Commands && _poller is null) + lock (_pollGate) { - _poller = Task.Run(PollLoopAsync); + if (!_options.IsUsable || !_options.Commands || _poller is { IsCompleted: false } || _cts.IsCancellationRequested) + { + return; + } + + _pollCts?.Dispose(); + _pollCts = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token); + CancellationToken token = _pollCts.Token; + _poller = Task.Run(() => PollLoopAsync(token)); } } + /// Stops the long-polling task (commands switched off in the settings); sending goes on. + public async Task StopCommandsAsync() + { + Task? poller; + CancellationTokenSource? cts; + lock (_pollGate) + { + poller = _poller; + cts = _pollCts; + _poller = null; + _pollCts = null; + } + + if (cts is null) + { + return; + } + + await cts.CancelAsync().ConfigureAwait(false); + try + { + if (poller is not null) + { + await poller.WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false); + } + } + catch (Exception ex) when (ex is OperationCanceledException or TimeoutException) + { + // Stopping anyway. + } + finally + { + cts.Dispose(); + } + } + + /// + /// Asks Telegram who the token belongs to (getMe): proves the token before it is + /// saved. Returns the bot's username; throws + /// with Telegram's own description when the token is refused. + /// + public static async Task GetMeAsync(string token, string baseUrl, HttpMessageHandler? handler, CancellationToken ct) + { + ArgumentException.ThrowIfNullOrWhiteSpace(token); + using HttpClient client = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false); + client.Timeout = TimeSpan.FromSeconds(20); + using HttpResponseMessage response = await client.GetAsync($"{(string.IsNullOrWhiteSpace(baseUrl) ? "https://api.telegram.org" : baseUrl).TrimEnd('/')}/bot{token.Trim()}/getMe", ct).ConfigureAwait(false); + string body = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + { + throw new InvalidOperationException($"Telegram ha rifiutato il token (HTTP {(int)response.StatusCode}: {Describe(body)})"); + } + + try + { + using JsonDocument doc = JsonDocument.Parse(body); + if (doc.RootElement.TryGetProperty("result", out JsonElement result) && result.TryGetProperty("username", out JsonElement user) && user.GetString() is { Length: > 0 } name) + { + return name; + } + } + catch (JsonException) + { + // Falls through to the error below. + } + + throw new InvalidOperationException($"risposta di getMe non riconosciuta: {Truncate(body)}"); + } + // ----------------------------------------------------------------------- // Sending // ----------------------------------------------------------------------- @@ -226,24 +342,25 @@ public sealed class TelegramNotifier : INotifier, IAsyncDisposable // Commands // ----------------------------------------------------------------------- - private async Task PollLoopAsync() + private async Task PollLoopAsync(CancellationToken ct) { - while (!_cts.IsCancellationRequested) + while (!ct.IsCancellationRequested) { try { - await PollOnceAsync(_cts.Token).ConfigureAwait(false); + await PollOnceAsync(ct).ConfigureAwait(false); } - catch (OperationCanceledException) + catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; } catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException) { + // A client timeout is a TaskCanceledException too: it is retried like a network error. _lastError = ex.Message; try { - await Task.Delay(TimeSpan.FromSeconds(10), _cts.Token).ConfigureAwait(false); + await Task.Delay(TimeSpan.FromSeconds(10), ct).ConfigureAwait(false); } catch (OperationCanceledException) { @@ -406,10 +523,11 @@ public sealed class TelegramNotifier : INotifier, IAsyncDisposable public async ValueTask DisposeAsync() { _queue.Writer.TryComplete(); + await StopCommandsAsync().ConfigureAwait(false); await _cts.CancelAsync().ConfigureAwait(false); try { - await Task.WhenAll(_sender, _poller ?? Task.CompletedTask).WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false); + await _sender.WaitAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false); } catch (Exception ex) when (ex is OperationCanceledException or TimeoutException) { diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Commands.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Commands.cs index d71a2d9..9424d54 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Commands.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Commands.cs @@ -75,22 +75,14 @@ public sealed partial class BasketEngine return new CommandResult(report.Flat, report.Flat ? $"kill-switch eseguito: {report.Summary}; nuove entrate bloccate fino al reset" : $"kill-switch con RESIDUO: {report.Summary}") { Payload = _haltResidue }; } - case EngineCommandKind.SetPreset: - if (!BasketPresets.TryParse(c.Argument, out PresetName preset)) - { - return new CommandResult(false, $"preset {c.Argument} sconosciuto"); - } - - _decider.SetPreset(preset); - Log.Info($"preset cambiato in {preset.ToString().ToUpperInvariant()} ({c.Reason}); i basket aperti non vengono toccati"); - _ledger.Correction(_runId, string.Empty, $"preset → {preset} ({c.Reason})"); - _notifier.Notify(NotificationKind.Event, "Preset cambiato", $"{preset.ToString().ToUpperInvariant()} ({TelegramEscape(c.Reason)}); i basket aperti non vengono toccati"); - return new CommandResult(true, $"preset {preset.ToString().ToUpperInvariant()} attivo"); + case EngineCommandKind.ApplySettings: + return ApplySettings(c); case EngineCommandKind.Pause: _pausedByOperator = true; - _entriesBlocked ??= "pausa dell'operatore"; - Log.Warn($"PAUSA ({c.Reason}): nessuna nuova entrata fino a /riprendi o al riavvio; le uscite restano attive"); + _entriesBlocked ??= PauseReason; + Log.Warn($"PAUSA ({c.Reason}): nessuna nuova entrata fino a /riprendi, anche dopo un riavvio; le uscite restano attive"); + SaveState(); return new CommandResult(true, "in pausa: nessuna nuova entrata, uscite attive"); case EngineCommandKind.Resume: @@ -100,11 +92,12 @@ public sealed partial class BasketEngine } _pausedByOperator = false; - if (_entriesBlocked == "pausa dell'operatore") + if (_entriesBlocked == PauseReason) { _entriesBlocked = null; } + SaveState(); Log.Info($"ripresa ({c.Reason}): entrate riabilitate{(_entriesBlocked is not null ? " salvo " + _entriesBlocked : string.Empty)}"); return new CommandResult(true, _entriesBlocked is null ? "entrate riabilitate" : $"pausa tolta, ma le entrate restano bloccate: {_entriesBlocked}"); @@ -136,6 +129,93 @@ public sealed partial class BasketEngine return i < 0 ? s : s[..i]; } + /// The reason the entries are blocked while the operator's pause is on. + private const string PauseReason = "pausa dell'operatore"; + + // ----------------------------------------------------------------------- + // Settings saved in Impostazioni (5.1, hot apply) + // ----------------------------------------------------------------------- + + /// + /// Takes a saved change on the decision thread, between two ticks: the eToro timeouts + /// of the private options, then strategy.json read again and copied in place into + /// the instance the decider, the executor and the learning state share. The preset in + /// force is recomputed (open baskets keep what they entered with), the switches of the + /// baskets are applied (a basket switched off keeps its exits), the fingerprint is + /// recomputed and a configurazione line records old and new in the ledger. A file + /// that changed the pairs or the direct crosses cannot be taken by a running engine: the + /// answer asks for a restart and nothing is applied. + /// + private CommandResult ApplySettings(EngineCommand c) + { + _etoro.FillTimeoutSeconds = _config.Etoro.FillTimeoutSeconds; + _etoro.RequestTimeoutSeconds = _config.Etoro.RequestTimeoutSeconds; + + BasketStrategyConfig fresh; + try + { + fresh = BasketStrategyConfig.Load(_strategyPath, out List warnings); + fresh.Validate(); + foreach (string w in warnings) + { + Log.Warn($"strategy.json: {w}"); + } + } + catch (Exception ex) when (ex is IOException or InvalidOperationException or System.Text.Json.JsonException or UnauthorizedAccessException) + { + Log.Warn($"impostazioni non applicate al motore: strategy.json non valido ({ex.Message})"); + return new CommandResult(false, $"strategy.json non valido: {ex.Message}"); + } + + fresh.InvertSignal = false; // research-only flag, never honoured by the bot + if (!fresh.SameStructure(_strategy)) + { + return new CommandResult(false, "la strategia cambia i basket o i cross diretti: serve un riavvio del motore") { Code = CommandResult.RestartRequired }; + } + + string before = _configHash; + string presetBefore = PresetLabel; + bool anchorsChanged = fresh.SignalMode != _strategy.SignalMode || fresh.AnchorBars != _strategy.AnchorBars; + _strategy.CopyFrom(fresh); + _decider.Reload(resetAnchors: anchorsChanged); + foreach (BasketSlot slot in _slots) + { + bool enabled = slot.Definition.Enabled && slot.Available; + if (enabled != slot.Enabled) + { + slot.Enabled = enabled; + slot.DisabledReason = DisabledReasonOf(slot.Definition.Enabled, slot.Available); + Log.Info($"[{slot.Name}] {(enabled ? "riattivato" : "disattivato: niente nuove entrate" + (slot.Position is not null ? ", il basket aperto resta seguito fino alla chiusura" : string.Empty))}"); + } + } + + _configHash = _strategy.Hash(); + string paths = c.Argument.Length > 0 ? c.Argument : "—"; + string what = string.Create(CultureInfo.InvariantCulture, + $"impostazioni applicate ({c.Reason}): {paths}; preset {presetBefore} → {PresetLabel}; impronta della strategia {before} → {_configHash}. I basket aperti tengono take-profit, perdita massima, zStop e aggiunte con cui sono entrati."); + _ledger.Note(_runId, "configurazione", string.Empty, what, w => + { + w.WriteString("config_hash_precedente", before); + w.WriteString("config_hash", _configHash); + w.WriteString("preset", PresetLabel); + w.WriteStartArray("chiavi"); + foreach (string p in c.Argument.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + w.WriteStringValue(p); + } + + w.WriteEndArray(); + }); + Log.Info(what); + if (before != _configHash || presetBefore != PresetLabel) + { + _notifier.Notify(NotificationKind.Event, "Impostazioni applicate", TelegramEscape($"preset {PresetLabel}, impronta {_configHash}; i basket aperti non cambiano")); + } + + SaveState(); + return new CommandResult(true, before == _configHash ? "applicato" : $"applicato: impronta della strategia {_configHash}"); + } + // ----------------------------------------------------------------------- // Bonifica (§5.5 of the 5.0 plan) // ----------------------------------------------------------------------- diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Realized.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Realized.cs index 64b3d63..1871c6f 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Realized.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Realized.cs @@ -106,11 +106,6 @@ public sealed partial class BasketEngine /// private async Task BackfillRealizedAsync(CancellationToken ct) { - if (_mode == ExecutionMode.Paper) - { - return; - } - try { RealizedBackfill backfill = new(_ledger, (from, token) => _broker.GetClosedTradesAsync(from, token), _runId, ModeLabel, diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Snapshot.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Snapshot.cs index bf24f4e..1dd64e1 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Snapshot.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.Snapshot.cs @@ -56,6 +56,8 @@ public sealed partial class BasketEngine Mode = _mode.Badge(), EnvironmentKind = _mode.Kind(), ExecutionMode = _mode.ToString(), + Account = _mode.Account(), + Paused = _pausedByOperator, Endpoint = _feed.Endpoint, Preset = PresetLabel, StrategyVersion = $"v{Assembly.GetExecutingAssembly().GetName().Version?.ToString(3) ?? "?"} · strategia {_configHash} · run {_runId}", @@ -143,22 +145,31 @@ public sealed partial class BasketEngine return row with { VolForecast = vol, MlState = ml, BanditProposal = _learning.BanditText + " (solo proposta)" }; } - /// The picture while the engine is not running. - public static BotSnapshot IdleSnapshot(BotConfig config, BotState state, string? error, EventRow[] events) + /// + /// The picture while the engine is not running. is the + /// cached strategy.json (the host's cache): without it the file is parsed here, + /// which the stream would do every second. + /// + public static BotSnapshot IdleSnapshot(BotConfig config, BasketStrategyConfig? strategy, BotState state, string? error, EventRow[] events) { ArgumentNullException.ThrowIfNull(config); ExecutionMode mode = config.Run.Mode; List rows = []; + string preset = "—"; + int maxBaskets = 0; try { - BasketStrategyConfig strategy = File.Exists(config.Run.StrategyPath) + strategy ??= File.Exists(config.Run.StrategyPath) ? BasketStrategyConfig.Load(config.Run.StrategyPath, out _) : BasketStrategyConfig.ParseText(BasketStrategyConfig.DefaultJson, out _); + BasketPreset effective = strategy.Effective(); + preset = effective.Label; + maxBaskets = effective.MaxBaskets; foreach (BasketDefinition d in strategy.Baskets) { string cross = SyntheticCross.TryDerive(d.A, d.B, out SyntheticCross? c) ? c!.Symbol : "?"; - rows.Add(new BasketRow(d.Name, d.A, d.B, cross, "fermo", 0, 0, 0, 0, strategy.Effective().TpPips, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, false, "—", - d.Enabled, d.Enabled ? string.Empty : "disattivato in strategy.json", "il bot è fermo", 0, 0, 0, false, double.NaN)); + rows.Add(new BasketRow(d.Name, d.A, d.B, cross, "fermo", 0, 0, 0, 0, effective.TpPips, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, false, "—", + d.Enabled, d.Enabled ? string.Empty : DisabledReasonOf(false, true), "il bot è fermo", 0, 0, 0, false, double.NaN)); } } catch (Exception ex) when (ex is IOException or InvalidOperationException or JsonException) @@ -173,8 +184,10 @@ public sealed partial class BasketEngine Mode = mode.Badge(), EnvironmentKind = mode.Kind(), ExecutionMode = mode.ToString(), + Account = mode.Account(), Endpoint = config.Etoro.BaseUrl, - Preset = "—", + Preset = preset, + MaxBaskets = maxBaskets, ApiState = "fermo", DisplayCurrency = config.Ui.DisplayCurrency, Events = events, diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs index 28ee76c..8027ab6 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.State.cs @@ -48,6 +48,11 @@ public sealed partial class BasketEngine // Today's realised result is not saved: it is recomputed from the venue's // history. What is saved is every close still waiting for it. _settlements.Queue.Write(w, "pendingSettlements"); + + // The operator's pause and a warm-up block survive a restart (5.1): a restart + // after a settings change, or the container's, must not lift them silently. + w.WriteBoolean("pausedByOperator", _pausedByOperator); + w.WriteString("entriesBlockedUntilUtc", _entriesBlockedUntilUtc is { } until ? until.ToString("O", CultureInfo.InvariantCulture) : string.Empty); w.WriteBoolean("killSwitched", _killSwitched); w.WriteBoolean("equityStopped", _equityStopped); w.WriteString("haltReason", _haltReason ?? string.Empty); @@ -87,6 +92,12 @@ public sealed partial class BasketEngine w.WriteNumber("entryCostPips", double.IsFinite(p.EntryCostPips) ? p.EntryCostPips : 0); w.WriteNumber("tpPips", p.TpPips); w.WriteNumber("maxLossUsd", p.MaxLossUsd); + if (double.IsFinite(p.ZStop)) + { + w.WriteNumber("zStop", p.ZStop); + } + + w.WriteNumber("maxAdds", p.MaxAdds); w.WriteNumber("equityAtEntry", p.EquityAtEntry); w.WriteNumber("accruedFeesUsd", p.AccruedFeesUsd); w.WriteString("entryMotivazione", p.EntryMotivazione); @@ -151,6 +162,21 @@ public sealed partial class BasketEngine DateTime lastBalanceUtc = root.TryGetProperty("lastBalanceUtc", out JsonElement lbu) && DateTime.TryParse(lbu.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t) ? t : default; _equity.Restore(peakNet, cash, lastBalance, lastBalanceUtc); + if (root.TryGetProperty("pausedByOperator", out JsonElement paused) && paused.ValueKind == JsonValueKind.True) + { + _pausedByOperator = true; + _entriesBlocked ??= PauseReason; + Log.Warn("pausa dell'operatore ancora attiva dal run precedente: nessuna nuova entrata fino a /riprendi; le uscite restano attive"); + } + + if (root.TryGetProperty("entriesBlockedUntilUtc", out JsonElement blockedUntil) && + DateTime.TryParse(blockedUntil.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime until) && + until > DateTime.UtcNow) + { + _entriesBlockedUntilUtc = until; + _entriesBlocked ??= string.Create(CultureInfo.InvariantCulture, $"riscaldamento fino alle {until:HH:mm} UTC (dal run precedente)"); + } + _killSwitched = root.TryGetProperty("killSwitched", out JsonElement ks) && ks.GetBoolean(); _equityStopped = root.TryGetProperty("equityStopped", out JsonElement es) && es.GetBoolean(); _haltReason = root.TryGetProperty("haltReason", out JsonElement hr) && hr.GetString() is { Length: > 0 } h ? h : null; @@ -216,6 +242,8 @@ public sealed partial class BasketEngine EntryCostPips = e.GetProperty("entryCostPips").GetDouble(), TpPips = e.GetProperty("tpPips").GetDouble(), MaxLossUsd = e.GetProperty("maxLossUsd").GetDouble(), + ZStop = e.TryGetProperty("zStop", out JsonElement zs) && zs.ValueKind == JsonValueKind.Number ? zs.GetDouble() : double.NaN, + MaxAdds = e.TryGetProperty("maxAdds", out JsonElement ma) && ma.ValueKind == JsonValueKind.Number ? ma.GetInt32() : -1, EquityAtEntry = e.GetProperty("equityAtEntry").GetDouble(), AccruedFeesUsd = e.GetProperty("accruedFeesUsd").GetDouble(), EntryMotivazione = e.GetProperty("entryMotivazione").GetString() ?? string.Empty, diff --git a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs index 704ab75..5ef1f68 100644 --- a/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs +++ b/Encelado/src/Encelado.Engine/Baskets/BasketEngine.cs @@ -60,11 +60,18 @@ public sealed partial class BasketEngine : IEngine private readonly BotConfig _config; private readonly BasketStrategyConfig _strategy; - private readonly string _configHash; + private readonly string _strategyPath; private readonly ExecutionMode _mode; + + /// + /// The engine's own copy of how to reach eToro, with the keys of the account it trades: + /// the shared configuration never carries keys, and a change of account or keys in the + /// settings restarts the engine instead of mixing two accounts under it. Only the + /// timeouts change in place (). + /// + private readonly EtoroOptions _etoro; private readonly EtoroBroker _feed; private readonly IBroker _broker; - private readonly PaperBroker? _paper; private readonly BasketDecider _decider; private readonly BasketExecutor _executor; private readonly OrderTracker _tracker; @@ -98,6 +105,9 @@ public sealed partial class BasketEngine : IEngine /// "P&L oggi": the bot's positions closed in the UTC day, from the venue's history plus the provisional estimates. private readonly RealizedToday _today = new(); + /// The strategy's fingerprint in the ledger; recomputed when a saved change is applied. + private string _configHash; + private AccountSnapshot _account = new(DateTime.MinValue, "USD", 0, 0, 0, 0, 0); private DateOnly _sessionDate; @@ -151,6 +161,9 @@ public sealed partial class BasketEngine : IEngine public bool Enabled { get; set; } = true; + /// Both instruments are quoted by the venue: the switch in the strategy alone decides. + public bool Available { get; init; } = true; + public string DisabledReason { get; set; } = string.Empty; public DateTime DisabledUntilUtc { get; set; } @@ -191,7 +204,10 @@ public sealed partial class BasketEngine : IEngine } } - public BasketEngine(BotConfig config, bool startConfirmed, IContextProvider? context = null, INotifier? notifier = null) + /// The shared configuration (no keys in it). + /// The keys of the account the mode trades on, from the secret store; null = none saved (the start fails with the reason). + /// A person typed the live phrase for this start; required for Live. + public BasketEngine(BotConfig config, EtoroKeys? keys, bool startConfirmed, IContextProvider? context = null, INotifier? notifier = null) { ArgumentNullException.ThrowIfNull(config); _config = config.Validate(); @@ -200,16 +216,16 @@ public sealed partial class BasketEngine : IEngine if (_mode.IsLive() && !startConfirmed) { - throw new InvalidOperationException($"la modalità {_mode} richiede la conferma esplicita all'avvio"); + throw new InvalidOperationException($"la modalità {_mode} richiede la frase {LiveConfirmation.Phrase} scritta all'avvio"); } - string strategyPath = config.Run.StrategyPath; - if (!File.Exists(strategyPath)) + _strategyPath = config.Run.StrategyPath; + if (!File.Exists(_strategyPath)) { - AppPaths.SeedStrategyFile(strategyPath); + AppPaths.SeedStrategyFile(_strategyPath); } - _strategy = BasketStrategyConfig.Load(strategyPath, out List warnings); + _strategy = BasketStrategyConfig.Load(_strategyPath, out List warnings); foreach (string w in warnings) { Log.Warn($"strategy.json: {w}"); @@ -220,10 +236,21 @@ public sealed partial class BasketEngine : IEngine _configHash = _strategy.Hash(); _runId = string.Create(CultureInfo.InvariantCulture, $"{DateTime.UtcNow:yyyyMMdd-HHmmss}-{Guid.NewGuid().ToString("N")[..6]}"); - KeyStores.Resolve(config, out string origin); - Log.Info($"chiavi eToro: {origin}"); + _etoro = new EtoroOptions + { + Environment = _mode.IsLive() ? "real" : "demo", + BaseUrl = config.Etoro.BaseUrl, + RequestTimeoutSeconds = config.Etoro.RequestTimeoutSeconds, + FillTimeoutSeconds = config.Etoro.FillTimeoutSeconds, + UserAgent = config.Etoro.UserAgent, + ApiKey = keys is { IsComplete: true } ? keys.ApiKey : string.Empty, + UserKey = keys is { IsComplete: true } ? keys.UserKey : string.Empty, + }; + Log.Info(keys is { IsComplete: true } + ? $"chiavi eToro del conto {(_etoro.IsDemo ? "demo" : "REALE")}: {KeyStores.Mask(keys.ApiKey)} (salvate il {keys.SavedUtc:yyyy-MM-dd})" + : $"nessuna chiave eToro per il conto {(_etoro.IsDemo ? "demo" : "reale")}"); - _feed = new EtoroBroker(config.Etoro) + _feed = new EtoroBroker(_etoro) { OnLog = static (message, ex) => { @@ -244,27 +271,20 @@ public sealed partial class BasketEngine : IEngine _stopFile = Path.Combine(config.Run.BaseDirectory, "STOP"); Directory.CreateDirectory(_marketDir); Directory.CreateDirectory(Path.GetDirectoryName(_statePath)!); + _broker = _feed; - if (_mode == ExecutionMode.Paper) + // The Paper simulator is gone (5.1): its files stay where they are, never read again. + foreach (string leftover in new[] { "paper_state.json", "pending_orders_paper.json" }) { - _paper = new PaperBroker(_feed, new PaperBrokerOptions + if (File.Exists(Path.Combine(_dataDir, "state", leftover))) { - StartingBalance = config.Run.PaperStartingBalance, - SlippagePips = config.Run.PaperSlippagePips, - OvernightPipsPerDay = _strategy.OvernightPipsPerDay, - StatePath = Path.Combine(_dataDir, "state", "paper_state.json"), - }); - _paper.PositionClosedByStop += (id, reason) => Log.Warn($"paper: posizione {id} chiusa dal simulatore ({reason})"); - _broker = _paper; - } - else - { - _broker = _feed; + Log.Info($"data/state/{leftover} è della modalità Paper, che non esiste più: il file resta dov'è e non viene letto"); + } } _ledger = new Ledger(Path.Combine(_dataDir, "ledger")); _origins = new PositionOrigins(_ledger.ReadOrders(), _ledger.ReadBaskets()); - _tracker = new OrderTracker(Path.Combine(_dataDir, "state", _mode == ExecutionMode.Paper ? "pending_orders_paper.json" : "pending_orders.json")); + _tracker = new OrderTracker(Path.Combine(_dataDir, "state", "pending_orders.json")); _tracker.Changed += (order, evento) => { OrderRecord line = OrderRecord.From(order, _runId, evento); @@ -362,8 +382,8 @@ public sealed partial class BasketEngine : IEngine if (!_feed.SupportsTrading) { _entriesBlocked = "nessuna chiave eToro: sessione in sola lettura"; - Log.Warn("nessuna chiave eToro: il motore parte in sola lettura e non può nemmeno leggere le quotazioni. Inserisci le chiavi dalla finestra di accesso."); - throw new InvalidOperationException("Servono le chiavi eToro (x-api-key e x-user-key) per leggere le quotazioni. Inseriscile dalla finestra di accesso."); + Log.Warn($"nessuna chiave eToro per il conto {(_etoro.IsDemo ? "demo" : "reale")}: il motore non può nemmeno leggere le quotazioni. Inseriscile da Impostazioni ▸ Conto."); + throw new InvalidOperationException($"Servono le chiavi eToro del conto {(_etoro.IsDemo ? "demo" : "reale")} (x-api-key e x-user-key) per leggere le quotazioni. Inseriscile da Impostazioni ▸ Conto."); } Stopwatch sw = Stopwatch.StartNew(); @@ -371,7 +391,7 @@ public sealed partial class BasketEngine : IEngine _apiLatencyMs = sw.Elapsed.TotalMilliseconds; _apiState = "connesso"; double skew = _feed.ClockSkew.TotalSeconds; - Log.Info(string.Create(CultureInfo.InvariantCulture, $"eToro: utente {_username}, ambiente {(_config.Etoro.IsDemo ? "DEMO" : "REALE")}, latenza {_apiLatencyMs:F0} ms, scarto orologio {skew:+0.0;-0.0} s")); + Log.Info(string.Create(CultureInfo.InvariantCulture, $"eToro: utente {_username}, conto {(_etoro.IsDemo ? "DEMO" : "REALE")}, latenza {_apiLatencyMs:F0} ms, scarto orologio {skew:+0.0;-0.0} s")); if (Math.Abs(skew) > _strategy.ClockSkewMaxSeconds) { _entriesBlocked = string.Create(CultureInfo.InvariantCulture, $"orologio locale sfasato di {skew:+0.0;-0.0} s rispetto al server (limite {_strategy.ClockSkewMaxSeconds} s)"); @@ -443,14 +463,18 @@ public sealed partial class BasketEngine : IEngine Cross = cross!, A = a ?? new SymbolSeries(new Instrument(0, d.A, d.A, "Forex", PipMath.Pip(d.A), PipMath.Digits(d.A), 0, 0, 0, [1], false, false, 0, 0, "mancante"), TimeSpan.FromMinutes(15), 500), B = b ?? new SymbolSeries(new Instrument(0, d.B, d.B, "Forex", PipMath.Pip(d.B), PipMath.Digits(d.B), 0, 0, 0, [1], false, false, 0, 0, "mancante"), TimeSpan.FromMinutes(15), 500), + Available = available, Enabled = d.Enabled && available, - DisabledReason = !d.Enabled ? "disattivato in strategy.json" : !available ? "uno dei due strumenti non è quotato da eToro" : string.Empty, + DisabledReason = DisabledReasonOf(d.Enabled, available), }; _slots.Add(slot); Log.Info($"[{slot.Name}] {cross!.Describe()}{(slot.Enabled ? string.Empty : " — DISATTIVATO: " + slot.DisabledReason)}"); } } + private static string DisabledReasonOf(bool enabled, bool available) => + !enabled ? "disattivato nella strategia (Impostazioni ▸ Strategia)" : !available ? "uno dei due strumenti non è quotato da eToro" : string.Empty; + private void WriteInstrumentsFile(IReadOnlyList instruments) { try @@ -461,7 +485,7 @@ public sealed partial class BasketEngine : IEngine { w.WriteStartObject(); w.WriteString("updatedUtc", DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture)); - w.WriteString("environment", _config.Etoro.Environment); + w.WriteString("environment", _etoro.Environment); w.WriteStartArray("instruments"); foreach (Instrument i in instruments) { @@ -560,15 +584,17 @@ public sealed partial class BasketEngine : IEngine private async Task LoopAsync(CancellationToken ct) { using PeriodicTimer timer = new(TimeSpan.FromSeconds(1)); - TimeSpan poll = TimeSpan.FromSeconds(_config.Run.PollSeconds); TimeSpan reconcile = TimeSpan.FromSeconds(ReconcileSeconds); - TimeSpan status = TimeSpan.FromSeconds(_config.Run.StatusSeconds); try { while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false)) { DateTime now = DateTime.UtcNow; + + // Read at every tick: a new interval saved in the settings applies at once. + TimeSpan poll = TimeSpan.FromSeconds(_config.Run.PollSeconds); + TimeSpan status = TimeSpan.FromSeconds(_config.Run.StatusSeconds); CheckInactivityOnTick(now); WriteHeartbeat(now); await DrainCommandsAsync(ct).ConfigureAwait(false); @@ -656,7 +682,8 @@ public sealed partial class BasketEngine : IEngine /// The hourly status at the top of every UTC hour and the daily summary at the configured hour. private void NotifyScheduled(DateTime now) { - if (_notifier is NullNotifier) + // Asked at every tick: Telegram can be switched on or off from the settings at any time. + if (!_notifier.IsActive) { return; } @@ -760,7 +787,8 @@ public sealed partial class BasketEngine : IEngine List<(BasketSlot Slot, BasketDecision Decision)> entries = []; foreach (BasketSlot slot in _slots) { - if (!slot.Enabled) + // A basket switched off keeps its exits: an open one is watched until it closes. + if (!BasketSlotPolicy.Evaluates(slot.Enabled, slot.Position is not null)) { continue; } @@ -801,7 +829,7 @@ public sealed partial class BasketEngine : IEngine bool first = true; foreach ((BasketSlot slot, BasketDecision decided) in entries) { - if (slot.State != BasketState.Idle || slot.Position is not null) + if (slot.State != BasketState.Idle || slot.Position is not null || !BasketSlotPolicy.MayExecute(slot.Enabled, DecisionKind.Enter)) { continue; } @@ -979,6 +1007,12 @@ public sealed partial class BasketEngine : IEngine break; case DecisionKind.Add: + if (!BasketSlotPolicy.MayExecute(slot.Enabled, d.Kind)) + { + slot.Intent = $"IN POSIZIONE, basket disattivato: niente aggiunte, uscite attive — {d.Motivazione}"; + break; + } + slot.Intent = "AGGIUNTA — " + d.Motivazione; if (isBarClose) { @@ -1507,11 +1541,6 @@ public sealed partial class BasketEngine : IEngine ReleaseInstanceLock(); _learning.Dispose(); _ledger.Dispose(); - if (_paper is not null) - { - await _paper.DisposeAsync().ConfigureAwait(false); - } - await _feed.DisposeAsync().ConfigureAwait(false); } } diff --git a/Encelado/src/Encelado.Engine/Baskets/HeadlessRunner.cs b/Encelado/src/Encelado.Engine/Baskets/HeadlessRunner.cs index 5c20005..91b83fa 100644 --- a/Encelado/src/Encelado.Engine/Baskets/HeadlessRunner.cs +++ b/Encelado/src/Encelado.Engine/Baskets/HeadlessRunner.cs @@ -13,7 +13,8 @@ namespace Encelado.Engine.Baskets; /// engine start, shutdown) lives in Encelado.Server.Program. /// /// Commands: status, close <basket>, kill, residuo [id], -/// preset <nome>, reset <motivazione>, bonifica, stop. +/// reset <motivazione>, bonifica, stop. The preset is not a +/// command since 5.1: it is part of the strategy, chosen in Impostazioni ▸ Strategia. /// /// public static class HeadlessRunner @@ -89,9 +90,6 @@ public static class HeadlessRunner case "residuo": result = await supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.CloseResidue, arg.Length > 0 ? arg : "all", "chiusura dei residui da console"), CancellationToken.None).ConfigureAwait(false); break; - case "preset": - result = await supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.SetPreset, arg, "cambio preset da console"), CancellationToken.None).ConfigureAwait(false); - break; case "reset": result = await supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.ResetEquityStop, string.Empty, arg), CancellationToken.None).ConfigureAwait(false); break; @@ -99,7 +97,7 @@ public static class HeadlessRunner await BonificaAsync(supervisor, stopping.Token).ConfigureAwait(false); continue; default: - Console.WriteLine("comandi: status, close , kill, residuo [id], preset , reset , bonifica, stop"); + Console.WriteLine("comandi: status, close , kill, residuo [id], reset , bonifica, stop (il preset si sceglie in Impostazioni ▸ Strategia)"); continue; } diff --git a/Encelado/src/Encelado.Engine/Baskets/HistoryService.cs b/Encelado/src/Encelado.Engine/Baskets/HistoryService.cs index 4abd3c3..b9427f9 100644 --- a/Encelado/src/Encelado.Engine/Baskets/HistoryService.cs +++ b/Encelado/src/Encelado.Engine/Baskets/HistoryService.cs @@ -12,10 +12,13 @@ namespace Encelado.Engine.Baskets; /// /// The sources of the Storico page, gathered and cached: the bot's own ledger files /// (orders.jsonl, baskets.csv, the cash movements of decisions.jsonl) -/// and the venue's history and open positions, read with the configured keys through -/// a read-only broker so the page works whether the engine runs or not. +/// and the venue's history and open positions, read through a read-only broker of its own +/// so the page works whether the engine runs or not. The account is the one the mode +/// trades on, the keys come from the secret store through (called +/// with demo true or false); drops the broker when the keys +/// or the account change, so the next read uses the new ones. /// -public sealed class HistoryService(BotConfig config) : IAsyncDisposable +public sealed class HistoryService(BotConfig config, Func? keys = null) : IAsyncDisposable { private static readonly TimeSpan CacheFor = TimeSpan.FromSeconds(30); @@ -87,28 +90,48 @@ public sealed class HistoryService(BotConfig config) : IAsyncDisposable private EtoroBroker Broker() { - if (_broker is null) + lock (_gate) { - EtoroOptions options = new() + if (_broker is null) { - Environment = config.Etoro.Environment, - BaseUrl = config.Etoro.BaseUrl, - RequestTimeoutSeconds = config.Etoro.RequestTimeoutSeconds, - ApiKey = config.Etoro.ApiKey, - UserKey = config.Etoro.UserKey, - UserAgent = config.Etoro.UserAgent, - }; - if (!options.HasKeys) - { - KeyStores.Resolve(config, out _); - options.ApiKey = config.Etoro.ApiKey; - options.UserKey = config.Etoro.UserKey; + bool demo = !config.Run.Mode.IsLive(); + EtoroKeys? k = keys?.Invoke(demo); + EtoroOptions options = new() + { + Environment = demo ? "demo" : "real", + BaseUrl = config.Etoro.BaseUrl, + RequestTimeoutSeconds = config.Etoro.RequestTimeoutSeconds, + ApiKey = k is { IsComplete: true } ? k.ApiKey : string.Empty, + UserKey = k is { IsComplete: true } ? k.UserKey : string.Empty, + UserAgent = config.Etoro.UserAgent, + }; + + _broker = new EtoroBroker(options) { OnLog = static (m, ex) => Log.Warn(ex is null ? m : $"{m}: {ex.Message}") }; } - _broker = new EtoroBroker(options) { OnLog = static (m, ex) => Log.Warn(ex is null ? m : $"{m}: {ex.Message}") }; + return _broker; + } + } + + /// + /// Forgets the broker and the cached rows: the keys or the account changed. The old + /// broker is closed a little later, so a page reading through it right now finishes. + /// + public void Invalidate() + { + EtoroBroker? old; + lock (_gate) + { + old = _broker; + _broker = null; + _cache = null; + _lastProblem = string.Empty; } - return _broker; + if (old is not null) + { + _ = Task.Delay(TimeSpan.FromSeconds(30)).ContinueWith(_ => old.DisposeAsync().AsTask(), TaskScheduler.Default).Unwrap(); + } } public List ReadOrders() @@ -169,9 +192,16 @@ public sealed class HistoryService(BotConfig config) : IAsyncDisposable public async ValueTask DisposeAsync() { - if (_broker is not null) + EtoroBroker? broker; + lock (_gate) { - await _broker.DisposeAsync().ConfigureAwait(false); + broker = _broker; + _broker = null; + } + + if (broker is not null) + { + await broker.DisposeAsync().ConfigureAwait(false); } } } diff --git a/Encelado/src/Encelado.Engine/Baskets/TelegramCommands.cs b/Encelado/src/Encelado.Engine/Baskets/TelegramCommands.cs index c33cea3..9d7233c 100644 --- a/Encelado/src/Encelado.Engine/Baskets/TelegramCommands.cs +++ b/Encelado/src/Encelado.Engine/Baskets/TelegramCommands.cs @@ -78,25 +78,3 @@ public sealed class TelegramCommands(BotSupervisor supervisor, Func noti private static string Text(CommandResult r) => (r.Ok ? "✅ " : "❌ ") + TelegramNotifier.Escape(r.Message); } - -/// Builds the notifier the configuration asks for: Telegram when usable, nothing otherwise. -public static class Notifications -{ - public static INotifier Create(Configuration.BotConfig config) - { - ArgumentNullException.ThrowIfNull(config); - TelegramOptions t = config.Notifications.Telegram; - if (!t.IsUsable) - { - if (t.Enabled) - { - Log.Warn("Telegram abilitato ma senza token o chat id (TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID): notifiche disattivate"); - } - - return NullNotifier.Instance; - } - - Log.Info(string.Create(CultureInfo.InvariantCulture, $"Telegram attivo: chat {t.ChatId}, stato orario {(t.HourlyStatus ? "sì" : "no")}, eventi {(t.EventAlerts ? "sì" : "no")}, riepilogo alle {t.DailySummaryUtcHour:00}:00 UTC, comandi {(t.Commands ? "sì" : "no")}")); - return new TelegramNotifier(t, null, static m => Log.Warn(m)); - } -} diff --git a/Encelado/src/Encelado.Engine/Configuration/AppPaths.cs b/Encelado/src/Encelado.Engine/Configuration/AppPaths.cs index 86c39c3..fb3db77 100644 --- a/Encelado/src/Encelado.Engine/Configuration/AppPaths.cs +++ b/Encelado/src/Encelado.Engine/Configuration/AppPaths.cs @@ -6,7 +6,7 @@ namespace Encelado.Engine.Configuration; /// Where the operator's files live and how they get there the first time. /// /// The configuration folder holds encelado.json, strategy.json, -/// instruments.json and the encrypted keys; everything the bot produces +/// instruments.json and the encrypted secrets (secrets.enc); everything the bot produces /// (data/, knowledge/, reports/, logs/) resolves against /// it unless the configuration says otherwise. In the container it is /config /// (and the data folder /data); anywhere else it is ENCELADO_CONFIG_DIR @@ -125,7 +125,11 @@ public static class AppPaths } } -/// The phrase that arms the live mode at every start, on the console (--confirm-live), in the container (ENCELADO_CONFIRM_LIVE) and in the web UI. +/// +/// The phrase that arms the live mode at every start (5.1, decision C7): typed by a person +/// in the interface, at AVVIA and before a change that restarts a Live engine. There is no +/// variable and no command-line switch for it: Live never starts without someone typing it. +/// public static class LiveConfirmation { public const string Phrase = "CONFERMO LIVE"; diff --git a/Encelado/src/Encelado.Engine/Configuration/BotConfig.cs b/Encelado/src/Encelado.Engine/Configuration/BotConfig.cs index a18a51a..3d4f4fb 100644 --- a/Encelado/src/Encelado.Engine/Configuration/BotConfig.cs +++ b/Encelado/src/Encelado.Engine/Configuration/BotConfig.cs @@ -4,20 +4,23 @@ using Encelado.Etoro; namespace Encelado.Engine.Configuration; /// -/// Everything the bot reads at startup. The file in Documents carries the operator's -/// choices; the secrets never do — they come from the encrypted store or the -/// environment and are filled into at runtime. The strategy's own -/// numbers live in strategy.json, next to this file. +/// Everything the bot reads from encelado.json. The file carries the operator's +/// choices, edited from Impostazioni; the secrets never do — the eToro keys and the +/// Telegram token live in the encrypted secret store, and whoever needs them builds a +/// private copy of the options (the engine, the history page, the notifier hub). One +/// instance lives for the whole process and is kept equal to the file after every save +/// (). The strategy's own numbers live in strategy.json, +/// next to this file. /// public sealed class BotConfig { - /// How to reach eToro; the keys are filled in at runtime from the encrypted store or the environment. + /// How to reach eToro. Never carries keys; the account (Environment) is derived from the execution mode. public EtoroOptions Etoro { get; set; } = new(); /// Execution mode and working folders. public RunOptions Run { get; set; } = new(); - /// What the window looks like: the time zone it shows. + /// What the interface shows and how. public UiOptions Ui { get; set; } = new(); public LoggingOptions Logging { get; set; } = new(); @@ -27,16 +30,68 @@ public sealed class BotConfig public BotConfig Validate() { - Etoro.Validate(); Run.Validate(); + + // One setting, two meanings (5.1, decision C6): the mode picks the account too, so + // a demo mode can never reach the real account without the Live gate. + Etoro.Environment = Run.Mode.IsLive() ? "real" : "demo"; + Etoro.Validate(); Ui.Validate(); Logging.Validate(); Notifications.Validate(); return this; } + + /// + /// Copies the values the operator edits from (the file just + /// saved, freshly loaded) into this live instance, in place: every object that holds a + /// section of it sees the new values at its next read. Never copied: the folders and + /// files (BaseDirectory, the data, knowledge and reports folders the container + /// remaps, strategyFile, the log folder and file), the endpoints (baseUrl, + /// userAgent) and any secret — those are fixed for the process. + /// + public void CopyFrom(BotConfig fresh) + { + ArgumentNullException.ThrowIfNull(fresh); + if (ReferenceEquals(fresh, this)) + { + return; + } + + Run.ExecutionMode = fresh.Run.ExecutionMode; + Run.AllowLive = fresh.Run.AllowLive; + Run.Autostart = fresh.Run.Autostart; + Run.PollSeconds = fresh.Run.PollSeconds; + Run.StatusSeconds = fresh.Run.StatusSeconds; + Run.CloseOnShutdown = fresh.Run.CloseOnShutdown; + + Etoro.Environment = fresh.Run.Mode.IsLive() ? "real" : "demo"; + Etoro.RequestTimeoutSeconds = fresh.Etoro.RequestTimeoutSeconds; + Etoro.FillTimeoutSeconds = fresh.Etoro.FillTimeoutSeconds; + + Ui.TimeZone = fresh.Ui.TimeZone; + Ui.DisplayCurrency = fresh.Ui.DisplayCurrency; + Ui.Theme = fresh.Ui.Theme; + Ui.NavExpanded = fresh.Ui.NavExpanded; + + Logging.Level = fresh.Logging.Level; + Logging.MaxFileSizeMb = fresh.Logging.MaxFileSizeMb; + Logging.MaxFiles = fresh.Logging.MaxFiles; + Logging.StatusLines = fresh.Logging.StatusLines; + Logging.BufferedLines = fresh.Logging.BufferedLines; + + Core.Notifications.TelegramOptions target = Notifications.Telegram; + Core.Notifications.TelegramOptions source = fresh.Notifications.Telegram; + target.Enabled = source.Enabled; + target.ChatId = source.ChatId; + target.HourlyStatus = source.HourlyStatus; + target.EventAlerts = source.EventAlerts; + target.DailySummaryUtcHour = source.DailySummaryUtcHour; + target.Commands = source.Commands; + } } -/// The notification channels (§7 of the 5.0 plan). Token and chat id come from the environment first. +/// The notification channels (§7 of the 5.0 plan). The chat id is here; the token lives in the secret store. public sealed class NotificationsOptions { public Core.Notifications.TelegramOptions Telegram { get; set; } = new(); @@ -62,12 +117,22 @@ public sealed class NotificationsOptions /// public sealed class RunOptions { - /// Paper, Demo (default) or Live. The bot trades by itself in every mode. + /// + /// Demo (default, the eToro demo account) or Live (the real account). The + /// bot trades by itself in both. The mode is also the account: there is no separate + /// environment setting since 5.1. + /// public string ExecutionMode { get; set; } = "Demo"; - /// Required, together with the typed phrase CONFERMO LIVE at start, for Live. + /// Required, together with the phrase CONFERMO LIVE typed in the interface at every start, for Live. public bool AllowLive { get; set; } + /// + /// Start the engine when the process starts (the container boots). Never in Live, which + /// always waits for AVVIA with the phrase. The command line --no-autostart wins. + /// + public bool Autostart { get; set; } = true; + /// Seconds between two quote polls (2-30; each poll is one request for all instruments). public int PollSeconds { get; set; } = 3; @@ -85,10 +150,6 @@ public sealed class RunOptions public string ReportsDirectory { get; set; } = "reports"; - public double PaperStartingBalance { get; set; } = 10_000; - - public double PaperSlippagePips { get; set; } = 0.3; - /// Set by the loader to the configuration file's folder. public string BaseDirectory { get; set; } = AppContext.BaseDirectory; @@ -109,7 +170,7 @@ public sealed class RunOptions { if (!ExecutionModeExtensions.TryParse(ExecutionMode, out ExecutionMode mode)) { - throw new InvalidOperationException("run.executionMode deve essere Paper, Demo oppure Live."); + throw new InvalidOperationException("run.executionMode deve essere Demo oppure Live."); } if (mode == Core.Baskets.ExecutionMode.Backtest) @@ -119,9 +180,11 @@ public sealed class RunOptions if (mode.IsLive() && !AllowLive) { - throw new InvalidOperationException("la modalità Live richiede run.allowLive = true (e la frase CONFERMO LIVE all'avvio)."); + throw new InvalidOperationException("la modalità Live richiede «Consenti il conto reale» (run.allowLive = true) e la frase CONFERMO LIVE a ogni avvio."); } + ExecutionMode = mode.ToString(); + if (PollSeconds is < 2 or > 30) { throw new InvalidOperationException("run.pollSeconds deve essere fra 2 e 30."); @@ -131,20 +194,10 @@ public sealed class RunOptions { throw new InvalidOperationException("run.statusSeconds deve essere fra 10 e 3600."); } - - if (PaperStartingBalance is <= 0 or > 1e9) - { - throw new InvalidOperationException("run.paperStartingBalance deve essere positivo."); - } - - if (PaperSlippagePips is < 0 or > 10) - { - throw new InvalidOperationException("run.paperSlippagePips deve essere fra 0 e 10."); - } } } -/// What the window shows and how. Nothing here changes what the bot does. +/// What the interface shows and how. Nothing here changes what the bot does. public sealed class UiOptions { /// The name that means "the computer's own time zone". @@ -160,7 +213,7 @@ public sealed class UiOptions /// The currencies the display selector offers (D-33). Every amount stays in USD underneath. public static readonly string[] Currencies = ["USD", "EUR", "GBP", "CHF", "JPY", "AUD", "CAD", "NZD"]; - /// The currency the web UI, Telegram and the exports show amounts in; the ledger stays in USD. + /// The currency the web interface shows amounts in; the ledger, the decisions, Telegram and the exports stay in USD. public string DisplayCurrency { get; set; } = "USD"; /// dark (default) or light. diff --git a/Encelado/src/Encelado.Engine/Configuration/ConfigDefaults.cs b/Encelado/src/Encelado.Engine/Configuration/ConfigDefaults.cs index 2678079..445539e 100644 --- a/Encelado/src/Encelado.Engine/Configuration/ConfigDefaults.cs +++ b/Encelado/src/Encelado.Engine/Configuration/ConfigDefaults.cs @@ -1,4 +1,5 @@ using System.Globalization; +using Encelado.Core.Baskets; namespace Encelado.Engine.Configuration; @@ -67,10 +68,9 @@ public static class ConfigDefaults config.Logging = factory.Logging; config.Notifications = factory.Notifications; - // Keys are never part of a default: they belong to the operator, not to the - // shipped configuration, and clearing them here would log the user out every - // time the file went missing. - config.Etoro.Environment = factory.Etoro.Environment; + // Keys are never part of a default (nor of the configuration): they live in the + // secret store. The account follows the mode, so there is no environment to copy. + config.Etoro.Environment = factory.Run.Mode.IsLive() ? "real" : "demo"; config.Etoro.BaseUrl = factory.Etoro.BaseUrl; config.Etoro.RequestTimeoutSeconds = factory.Etoro.RequestTimeoutSeconds; config.Etoro.FillTimeoutSeconds = factory.Etoro.FillTimeoutSeconds; @@ -101,41 +101,40 @@ public static class ConfigDefaults /// The factory encelado.json, byte for byte what ships in config/. public const string Json = """ { - "_commento": "Configurazione di Encelado — Correlation Baskets su eToro (CFD forex). Le chiavi con il prefisso _ sono documentazione e vengono ignorate. I parametri della strategia (basket, preset, soglie, rischio) stanno in strategy.json accanto a questo file. Le chiavi API non stanno qui: si inseriscono dalla finestra e vivono cifrate in %LOCALAPPDATA%\\Encelado\\etoro.dat, oppure nelle variabili d'ambiente ETORO_API_KEY e ETORO_USER_KEY.", + "_commento": "Configurazione di Encelado — Correlation Baskets su eToro (CFD forex). Si modifica da Impostazioni nell'interfaccia web, che applica subito tutto quello che può (quando serve riavvia il motore da sé, senza chiudere i basket). Le chiavi con il prefisso _ sono documentazione e vengono ignorate. I parametri della strategia (basket, preset, soglie, rischio) stanno in strategy.json accanto a questo file. Le chiavi eToro e il token Telegram non stanno qui: si inseriscono da Impostazioni e vivono cifrati in secrets.enc con la password dell'interfaccia.", "etoro": { - "_note": "eToro Public API. environment = demo oppure real: chiavi e rotte sono diverse, e l'ambiente attivo è sempre visibile nella finestra.", - "environment": "demo", + "_note": "eToro Public API. Il conto segue run.executionMode: Demo = conto demo, Live = conto reale; chiavi e rotte dei due conti sono diverse e il conto attivo è sempre visibile nell'interfaccia.", "baseUrl": "https://public-api.etoro.com", + "_requestTimeoutSeconds": "Oltre questo tempo una richiesta HTTP a eToro viene abbandonata (e, se era una lettura, ritentata).", "requestTimeoutSeconds": 20, "_fillTimeoutSeconds": "Quanto attendere l'esito di un ordine (eToro lo lavora in modo asincrono) prima di trattarlo come non confermato e riconciliare. È anche il timeout della seconda gamba (leg-risk).", "fillTimeoutSeconds": 5 }, "run": { - "_executionMode": "Paper = simulatore locale sopra le quotazioni reali (nessun ordine sul conto). Demo = conto demo di eToro: ordini veri, denaro virtuale, il bot apre e chiude da solo. Live = conto reale: richiede allowLive = true e la frase CONFERMO LIVE a ogni avvio. Nessuna modalità chiede l'approvazione dei singoli ordini (decisione D-20).", + "_executionMode": "Demo = conto demo di eToro: ordini veri, denaro virtuale, il bot apre e chiude da solo. Live = conto reale: richiede allowLive = true e la frase CONFERMO LIVE scritta nell'interfaccia a ogni avvio; in Live il motore non parte mai da solo. Il cambio di conto è rifiutato finché ci sono basket aperti o ordini in sospeso. Nessuna modalità chiede l'approvazione dei singoli ordini (decisione D-20).", "executionMode": "Demo", "allowLive": false, + "_autostart": "true = all'avvio del container il motore parte da solo (mai in Live, che aspetta AVVIA con la frase). false = il motore parte solo con AVVIA.", + "autostart": true, "_pollSeconds": "Secondi fra due letture delle quotazioni (una richiesta per tutti gli strumenti). 3 s = 20 richieste al minuto su una quota di 120: resta spazio per candele e costi.", "pollSeconds": 3, - "_statusSeconds": "Ogni quanti secondi il bot scrive una riga di stato nel log (e sulla console in headless).", + "_statusSeconds": "Ogni quanti secondi il bot scrive una riga di stato nel log (e sulla console).", "statusSeconds": 60, - "_closeOnShutdown": "true = fermare il bot chiude i basket aperti a mercato. false = restano sul conto con gli stop nativi sul server, senza nessuno che applichi il take-profit o lo stop di basket finché il bot non riparte.", + "_closeOnShutdown": "true = fermare il bot chiude i basket aperti a mercato. false = restano sul conto con gli stop nativi sul server, senza nessuno che applichi il take-profit o lo stop di basket finché il bot non riparte. Un riavvio automatico dopo un cambio delle impostazioni non chiude mai niente.", "closeOnShutdown": false, "strategyFile": "strategy.json", - "_cartelle": "Relative alla cartella di questo file: data (mercato, calendario, notizie, ledger, modelli), knowledge (calibrazione, proposte, registri), reports.", + "_cartelle": "Relative alla cartella di questo file: data (mercato, calendario, notizie, ledger, modelli), knowledge (calibrazione, proposte, registri), reports. Nel container stanno in /data.", "dataDirectory": "data", "knowledgeDirectory": "knowledge", - "reportsDirectory": "reports", - "_paper": "Solo per executionMode = Paper: saldo iniziale del simulatore e slippage per gamba oltre lo spread reale del momento.", - "paperStartingBalance": 10000, - "paperSlippagePips": 0.3 + "reportsDirectory": "reports" }, "ui": { - "_timeZone": "Fuso orario con cui l'interfaccia mostra gli orari. 'computer' = quello del sistema (nel container la variabile TZ); 'UTC'; oppure un id IANA (es. 'Europe/Rome'). Il file di log porta l'offset, il ledger è in UTC: cambiare questo valore non tocca nessun file.", + "_timeZone": "Fuso degli orari scritti dal server (righe di attività, riga di stato): 'computer' = quello del sistema; 'UTC'; oppure un id IANA (es. 'Europe/Rome'). Gli orologi dell'interfaccia usano il fuso del browser; il file di log porta l'offset e il ledger è in UTC.", "timeZone": "computer", - "_displayCurrency": "Valuta in cui l'interfaccia, Telegram e le esportazioni mostrano gli importi (USD, EUR, GBP, CHF, JPY, AUD, CAD, NZD). I tassi vengono dalle quotazioni eToro già in polling; ledger e decisioni restano in USD. Anche ENCELADO_DISPLAY_CURRENCY.", + "_displayCurrency": "Valuta in cui l'interfaccia mostra gli importi (USD, EUR, GBP, CHF, JPY, AUD, CAD, NZD). I tassi vengono dalle quotazioni eToro già in polling; ledger e decisioni restano in USD.", "displayCurrency": "USD", "_theme": "dark oppure light.", "theme": "dark", @@ -159,7 +158,7 @@ public static class ConfigDefaults }, "notifications": { - "_telegram": "Notifiche e comandi su Telegram (5.0). Il token del bot NON si scrive qui: variabile d'ambiente TELEGRAM_BOT_TOKEN (e TELEGRAM_CHAT_ID, che ha la precedenza su chatId). hourlyStatus = stato allo scoccare di ogni ora UTC; eventAlerts = aperture, chiusure, ordini risolti, kill-switch, recupero, errori; dailySummaryUtcHour = ora UTC del riepilogo giornaliero (negativo = spento); commands = risposte ai comandi /stato, /posizioni, /storico, /pausa, /riprendi, /chiudi, /kill CONFERMO, /reset dalla sola chat autorizzata.", + "_telegram": "Notifiche e comandi su Telegram. Il token del bot si inserisce da Impostazioni ▸ Notifiche Telegram e vive cifrato in secrets.enc, mai in questo file; chatId è la sola chat che riceve i messaggi e può dare comandi. hourlyStatus = stato allo scoccare di ogni ora UTC; eventAlerts = aperture, chiusure, ordini risolti, kill-switch, recupero, errori; dailySummaryUtcHour = ora UTC del riepilogo giornaliero (negativo = spento); commands = risposte ai comandi /stato, /posizioni, /storico, /pausa, /riprendi, /chiudi, /kill CONFERMO, /reset dalla sola chat autorizzata.", "telegram": { "enabled": false, "chatId": "", diff --git a/Encelado/src/Encelado.Engine/Configuration/ConfigLoader.cs b/Encelado/src/Encelado.Engine/Configuration/ConfigLoader.cs index b4e2bf4..ce01f8b 100644 --- a/Encelado/src/Encelado.Engine/Configuration/ConfigLoader.cs +++ b/Encelado/src/Encelado.Engine/Configuration/ConfigLoader.cs @@ -4,13 +4,22 @@ using Encelado.Core.Baskets; namespace Encelado.Engine.Configuration; +/// What the configuration files of a previous version said about secrets: import sources, never settings. +public sealed record LegacyFileSecrets(string ApiKey, string UserKey, string TelegramToken) +{ + public bool HasEtoroKeys => ApiKey.Length > 0 && UserKey.Length > 0; +} + /// /// Reads encelado.json by hand with . No reflection /// binder means no trimming surprises and no silent type coercion — an unknown key is /// reported instead of ignored. /// -/// Precedence: file < local overlay < environment variables. Credentials live in -/// the encrypted store or in the environment, never in the committed config. +/// Precedence: file < local overlay (encelado.local.json). Since 5.1 no +/// environment variable changes a setting: everything is set from the interface, and the +/// variables of 5.0 are imported once at startup () and +/// then ignored. Secrets are never read from a file into the configuration: the keys a +/// file of 5.0 may still carry are reported and handed to the import instead. /// /// public static class ConfigLoader @@ -27,10 +36,32 @@ public static class ConfigLoader "binance", "alpaca", "pairs", "ml", "ctrader", "engine", "strategy", "risk", "storage", "symbols", }; + /// + /// Keys of 5.0 that no longer exist, removed from the file at the next save from the + /// interface (with the documentation lines that described them). The secrets a file + /// may carry are not here: the import moves them to the store first. + /// + public static readonly IReadOnlyList ObsoleteKeys = + [ + "etoro.environment", + "run.paperStartingBalance", + "run.paperSlippagePips", + "run._paper", + ]; + + /// The secret keys a file of 5.0 could hold, removed from the main file once the import has stored them. + public static readonly IReadOnlyList SecretKeys = + [ + "etoro.apiKey", + "etoro.userKey", + "notifications.telegram.botToken", + ]; + public static BotConfig Load(string path, out List warnings) { warnings = []; BotConfig config = new(); + ParseState state = new(); // Relative output paths anchor to the configuration's own folder, so a config in // Documents keeps its logs beside it instead of beside the executable. @@ -45,24 +76,24 @@ public static class ConfigLoader { using FileStream stream = File.OpenRead(path); using JsonDocument doc = JsonDocument.Parse(stream, ParseOptions); - ApplyJson(config, doc.RootElement, warnings); + ApplyJson(config, doc.RootElement, warnings, state); } else { - warnings.Add($"configurazione '{path}' non trovata; uso i valori di fabbrica e le variabili d'ambiente"); + warnings.Add($"configurazione '{path}' non trovata; uso i valori di fabbrica"); ConfigDefaults.ApplyTo(config); } // A sibling *.local.json overlays machine-specific overrides. - string localPath = Path.ChangeExtension(path, null) + ".local.json"; + string localPath = LocalPath(path); if (File.Exists(localPath)) { using FileStream stream = File.OpenRead(localPath); using JsonDocument doc = JsonDocument.Parse(stream, ParseOptions); - ApplyJson(config, doc.RootElement, warnings); + ApplyJson(config, doc.RootElement, warnings, state); } - ApplyEnvironment(config); + MergeModeAndAccount(config, state, warnings); config.Ui.ResolveTimeZone(out string? zoneWarning); if (zoneWarning is not null) @@ -73,7 +104,158 @@ public static class ConfigLoader return config; } - private static void ApplyJson(BotConfig config, JsonElement root, List warnings) + /// The overlay beside a configuration file: encelado.local.json. + public static string LocalPath(string path) => Path.ChangeExtension(path, null) + ".local.json"; + + /// + /// The secrets a file of 5.0 may carry (the main file or the overlay; the overlay + /// wins): read only by the one-time import, which moves them to the encrypted store. + /// + public static LegacyFileSecrets ReadLegacySecrets(string path) + { + string api = string.Empty, user = string.Empty, token = string.Empty; + foreach (string file in new[] { path, LocalPath(path) }) + { + if (!TryRead(file, out JsonDocument? doc)) + { + continue; + } + + using (doc) + { + JsonElement root = doc!.RootElement; + if (Section(root, "etoro") is { } etoro) + { + api = Text(etoro, "apiKey") ?? api; + user = Text(etoro, "userKey") ?? user; + } + + if (Section(root, "notifications") is { } notifications && Section(notifications, "telegram") is { } telegram) + { + token = Text(telegram, "botToken") ?? token; + } + } + } + + return new LegacyFileSecrets(api.Trim(), user.Trim(), token.Trim()); + } + + /// + /// The raw run.executionMode and etoro.environment of the files, before + /// the merge (null when absent): the import needs them to route the keys of 5.0. + /// + public static (string? Mode, string? Environment) ReadRawModeAndEnvironment(string path) + { + string? mode = null, environment = null; + foreach (string file in new[] { path, LocalPath(path) }) + { + if (!TryRead(file, out JsonDocument? doc)) + { + continue; + } + + using (doc) + { + JsonElement root = doc!.RootElement; + if (Section(root, "run") is { } run) + { + mode = Text(run, "executionMode") ?? mode; + } + + if (Section(root, "etoro") is { } etoro) + { + environment = Text(etoro, "environment") ?? environment; + } + } + } + + return (mode, environment); + } + + private static bool TryRead(string file, out JsonDocument? doc) + { + doc = null; + if (!File.Exists(file)) + { + return false; + } + + try + { + doc = JsonDocument.Parse(File.ReadAllText(file), ParseOptions); + return doc.RootElement.ValueKind == JsonValueKind.Object || Dispose(doc); + } + catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException) + { + return false; + } + + static bool Dispose(JsonDocument d) + { + d.Dispose(); + return false; + } + } + + private static JsonElement? Section(JsonElement e, string name) + { + foreach (JsonProperty p in e.EnumerateObject()) + { + if (p.Name.Equals(name, StringComparison.OrdinalIgnoreCase) && p.Value.ValueKind == JsonValueKind.Object) + { + return p.Value; + } + } + + return null; + } + + private static string? Text(JsonElement e, string name) + { + foreach (JsonProperty p in e.EnumerateObject()) + { + if (p.Name.Equals(name, StringComparison.OrdinalIgnoreCase) && p.Value.ValueKind == JsonValueKind.String) + { + return p.Value.GetString(); + } + } + + return null; + } + + /// What the passes over the file and the overlay found that the merge needs. + private sealed class ParseState + { + public string? Environment { get; set; } + } + + /// + /// The mode is the account (5.1, decision C6). A file of 5.0 with etoro.environment + /// is merged: Live only when the mode is Live and the account real, Demo otherwise, with + /// a warning when the two disagreed. The key leaves the file at the next save. + /// + private static void MergeModeAndAccount(BotConfig config, ParseState state, List warnings) + { + if (state.Environment is null) + { + return; + } + + ExecutionModeExtensions.TryParse(config.Run.ExecutionMode, out ExecutionMode mode); + ExecutionMode merged = ExecutionModeExtensions.Merge(mode, state.Environment, out bool disagree); + if (disagree) + { + warnings.Add($"run.executionMode '{config.Run.ExecutionMode}' ed etoro.environment '{state.Environment}' non erano d'accordo: letto come {merged}. Dalla 5.1 la modalità sceglie anche il conto (Demo = conto demo, Live = conto reale)."); + } + else + { + warnings.Add($"etoro.environment non esiste più: il conto segue la modalità ({merged}). La chiave sparisce dal file al prossimo salvataggio."); + } + + config.Run.ExecutionMode = merged.ToString(); + } + + private static void ApplyJson(BotConfig config, JsonElement root, List warnings, ParseState state) { if (root.ValueKind != JsonValueKind.Object) { @@ -90,7 +272,7 @@ public static class ConfigLoader switch (section.Name.ToLowerInvariant()) { case "etoro": - ReadEtoro(config, section.Value, warnings); + ReadEtoro(config, section.Value, warnings, state); break; case "run": ReadRun(config, section.Value, warnings); @@ -123,22 +305,21 @@ public static class ConfigLoader } } - private static void ReadEtoro(BotConfig config, JsonElement e, List warnings) + private static void ReadEtoro(BotConfig config, JsonElement e, List warnings, ParseState state) { Etoro.EtoroOptions o = config.Etoro; foreach (JsonProperty p in Properties(e, "etoro", warnings)) { switch (p.Name.ToLowerInvariant()) { - case "environment": o.Environment = Str(p); break; + case "environment": state.Environment = Str(p).Trim().ToLowerInvariant(); break; case "baseurl": o.BaseUrl = Str(p); break; case "requesttimeoutseconds": o.RequestTimeoutSeconds = Int(p); break; case "filltimeoutseconds": o.FillTimeoutSeconds = Int(p); break; case "useragent": o.UserAgent = Str(p); break; - - // Accepted for a *.local.json overlay, never written by the app. - case "apikey": o.ApiKey = Str(p); break; - case "userkey": o.UserKey = Str(p); break; + case "apikey" or "userkey": + warnings.Add($"la chiave 'etoro.{p.Name}' in un file è ignorata: le chiavi eToro si inseriscono da Impostazioni ▸ Conto e vivono cifrate in secrets.enc"); + break; default: warnings.Add($"chiave sconosciuta 'etoro.{p.Name}'"); break; } } @@ -156,12 +337,15 @@ public static class ConfigLoader if (ExecutionModeExtensions.IsLegacyName(o.ExecutionMode)) { ExecutionModeExtensions.TryParse(o.ExecutionMode, out ExecutionMode mapped); - warnings.Add($"run.executionMode '{o.ExecutionMode}' è di una versione precedente: letto come {mapped}. Le approvazioni manuali non esistono più (D-20)."); + warnings.Add(o.ExecutionMode.Trim().Equals("paper", StringComparison.OrdinalIgnoreCase) + ? $"run.executionMode 'Paper' non esiste più (il conto demo di eToro è il simulatore): letto come {mapped}." + : $"run.executionMode '{o.ExecutionMode}' è di una versione precedente: letto come {mapped}. Le approvazioni manuali non esistono più (D-20)."); o.ExecutionMode = mapped.ToString(); } break; case "allowlive": o.AllowLive = Bool(p); break; + case "autostart": o.Autostart = Bool(p); break; case "pollseconds": o.PollSeconds = Int(p); break; case "statusseconds": o.StatusSeconds = Int(p); break; case "closeonshutdown": o.CloseOnShutdown = Bool(p); break; @@ -169,8 +353,9 @@ public static class ConfigLoader case "datadirectory": o.DataDirectory = Str(p); break; case "knowledgedirectory": o.KnowledgeDirectory = Str(p); break; case "reportsdirectory": o.ReportsDirectory = Str(p); break; - case "paperstartingbalance": o.PaperStartingBalance = Num(p); break; - case "paperslippagepips": o.PaperSlippagePips = Num(p); break; + case "paperstartingbalance" or "paperslippagepips": + warnings.Add($"la chiave 'run.{p.Name}' apparteneva alla modalità Paper, che non esiste più: ignorata (sparisce dal file al prossimo salvataggio)."); + break; case "allowdemoauto": warnings.Add("la chiave 'run.allowDemoAuto' appartiene a una versione precedente ed è stata ignorata: in Demo il bot opera da solo."); break; @@ -240,70 +425,15 @@ public static class ConfigLoader case "dailysummaryutchour": t.DailySummaryUtcHour = Int(p); break; case "commands": t.Commands = Bool(p); break; case "baseurl": t.BaseUrl = Str(p); break; - - // Accepted for a *.local.json overlay or the operator's own file, never written by the app. - case "bottoken": t.BotToken = Str(p).Trim(); break; + case "bottoken": + warnings.Add("la chiave 'notifications.telegram.botToken' in un file è ignorata: il token si inserisce da Impostazioni ▸ Notifiche Telegram e vive cifrato in secrets.enc"); + break; default: warnings.Add($"chiave sconosciuta 'notifications.telegram.{p.Name}'"); break; } } } } - private static void ApplyEnvironment(BotConfig config) - { - // Telegram: the token never lives in a committed file; the chat id may. - string? telegramToken = Environment.GetEnvironmentVariable("TELEGRAM_BOT_TOKEN"); - if (!string.IsNullOrWhiteSpace(telegramToken)) - { - config.Notifications.Telegram.BotToken = telegramToken.Trim(); - } - - string? telegramChat = Environment.GetEnvironmentVariable("TELEGRAM_CHAT_ID"); - if (!string.IsNullOrWhiteSpace(telegramChat)) - { - config.Notifications.Telegram.ChatId = telegramChat.Trim(); - } - - // eToro keys for automation (a VPS service): never written anywhere by the app. - string? apiKey = Environment.GetEnvironmentVariable("ETORO_API_KEY"); - string? userKey = Environment.GetEnvironmentVariable("ETORO_USER_KEY"); - if (!string.IsNullOrWhiteSpace(apiKey) && !string.IsNullOrWhiteSpace(userKey)) - { - config.Etoro.ApiKey = apiKey.Trim(); - config.Etoro.UserKey = userKey.Trim(); - } - - string? etoroEnvironment = Environment.GetEnvironmentVariable("ETORO_ENVIRONMENT"); - if (!string.IsNullOrWhiteSpace(etoroEnvironment)) - { - config.Etoro.Environment = etoroEnvironment.Trim().ToLowerInvariant(); - } - - string? executionMode = Environment.GetEnvironmentVariable("ENCELADO_EXECUTION_MODE"); - if (!string.IsNullOrWhiteSpace(executionMode)) - { - config.Run.ExecutionMode = ExecutionModeExtensions.TryParse(executionMode, out ExecutionMode m) ? m.ToString() : executionMode.Trim(); - } - - string? level = Environment.GetEnvironmentVariable("ENCELADO_LOG_LEVEL"); - if (!string.IsNullOrWhiteSpace(level)) - { - config.Logging.Level = level.Trim(); - } - - string? zone = Environment.GetEnvironmentVariable("ENCELADO_TIME_ZONE") ?? Environment.GetEnvironmentVariable("TZ"); - if (!string.IsNullOrWhiteSpace(zone) && config.Ui.TimeZone.Equals(UiOptions.ComputerZone, StringComparison.OrdinalIgnoreCase)) - { - config.Ui.TimeZone = zone.Trim(); - } - - string? currency = Environment.GetEnvironmentVariable("ENCELADO_DISPLAY_CURRENCY"); - if (!string.IsNullOrWhiteSpace(currency)) - { - config.Ui.DisplayCurrency = currency.Trim().ToUpperInvariant(); - } - } - private static IEnumerable Properties(JsonElement e, string section, List warnings) { if (e.ValueKind != JsonValueKind.Object) diff --git a/Encelado/src/Encelado.Engine/Configuration/ConfigWriter.cs b/Encelado/src/Encelado.Engine/Configuration/ConfigWriter.cs index a619c3b..de90e5d 100644 --- a/Encelado/src/Encelado.Engine/Configuration/ConfigWriter.cs +++ b/Encelado/src/Encelado.Engine/Configuration/ConfigWriter.cs @@ -1,26 +1,34 @@ +using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Nodes; namespace Encelado.Engine.Configuration; /// -/// Targeted edits to encelado.json made from the settings screen. +/// Targeted edits to encelado.json and strategy.json made from the settings +/// screen. /// -/// The file is parsed into a tree, one value is replaced, and -/// the tree is written back. Serialising a instead would be +/// The file is parsed into a tree, values are replaced or removed, +/// and the tree is written back. Serialising a instead would be /// simpler and wrong: it would silently delete every key the loader does not model — /// including the _-prefixed lines that document what each number is for and why /// it has that value — and reorder everything else. /// /// -/// The write goes to a temporary file first and is then moved into place, so a failure -/// halfway through leaves the previous configuration intact rather than a truncated -/// file the application cannot start from. +/// The text is written with the relaxed encoder: accented letters and symbols (è, ρ, ×, +/// ≥, the apostrophe) stay readable in a hand-edited file instead of becoming +/// è. The write goes to a temporary file first and is then moved into place, +/// so a failure halfway through leaves the previous file intact rather than a truncated +/// one the application cannot start from. /// /// public static class ConfigWriter { - private static readonly JsonWriterOptions WriteOptions = new() { Indented = true }; + private static readonly JsonWriterOptions WriteOptions = new() + { + Indented = true, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; private static readonly JsonDocumentOptions ReadOptions = new() { @@ -31,10 +39,11 @@ public static class ConfigWriter /// /// Writes a batch of values addressed by dotted path, in one atomic save. /// - /// Paths look like risk.stakePct, engine.timeFrame or - /// symbols[0].parameters.period. Missing intermediate objects are created; - /// missing array elements are an error, because inventing a symbol out of a typo - /// would be worse than refusing. + /// Paths look like run.pollSeconds, risk.maxMarginUsePct or + /// baskets[0].enabled. Missing intermediate objects are created; missing array + /// elements are an error, because inventing a basket out of a typo would be worse than + /// refusing. are removed from the file (a missing key is + /// not an error: removing it again changes nothing). /// /// /// A batch is all-or-nothing on purpose. Applying half a settings screen would leave @@ -43,12 +52,12 @@ public static class ConfigWriter /// the next start. /// /// - public static void Apply(string configPath, IReadOnlyDictionary changes) + public static void Apply(string configPath, IReadOnlyDictionary changes, IReadOnlyCollection? deletions = null) { ArgumentException.ThrowIfNullOrWhiteSpace(configPath); ArgumentNullException.ThrowIfNull(changes); - if (changes.Count == 0) + if (changes.Count == 0 && (deletions is null || deletions.Count == 0)) { return; } @@ -59,9 +68,98 @@ public static class ConfigWriter { SetPath(root, path, value); } + + foreach (string path in deletions ?? []) + { + DeletePath(root, path); + } }); } + /// + /// The documentation lines (keys beginning with _, in the file and in its + /// sections) whose text in the file differs from the factory's: path → the factory text. + /// A file written by an older version keeps explaining settings that changed meaning (a + /// variable that is no longer read, a mode that no longer exists); a save refreshes + /// those lines, and only those present in both — the values are never touched. + /// + public static Dictionary DocumentationUpdates(string path, string factoryJson) + { + Dictionary updates = new(StringComparer.Ordinal); + try + { + if (!File.Exists(path) || + JsonNode.Parse(File.ReadAllText(path), documentOptions: ReadOptions) is not JsonObject file || + JsonNode.Parse(factoryJson, documentOptions: ReadOptions) is not JsonObject factory) + { + return updates; + } + + Walk(file, factory, string.Empty, depth: 0); + } + catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException) + { + // Nothing to refresh in a file that cannot be read: the save itself will say why. + } + + return updates; + + void Walk(JsonObject file, JsonObject factory, string prefix, int depth) + { + foreach ((string name, JsonNode? value) in factory) + { + if (!file.TryGetPropertyValue(name, out JsonNode? current)) + { + continue; + } + + if (name.StartsWith('_') && value is JsonValue v && v.TryGetValue(out string? text) && + current is JsonValue c && c.TryGetValue(out string? old) && !string.Equals(text, old, StringComparison.Ordinal)) + { + updates[prefix + name] = JsonValue.Create(text); + } + else if (depth < 2 && value is JsonObject childFactory && current is JsonObject childFile) + { + Walk(childFile, childFactory, prefix + name + ".", depth + 1); + } + } + } + } + + /// Whether the file holds a value at (for the obsolete keys worth removing). + public static bool Contains(string configPath, string path) + { + if (!File.Exists(configPath)) + { + return false; + } + + try + { + JsonNode? current = JsonNode.Parse(File.ReadAllText(configPath), documentOptions: ReadOptions); + foreach (string segment in path.Split('.', StringSplitOptions.RemoveEmptyEntries)) + { + (string name, int? index) = Parse(segment); + current = current is JsonObject o && o.TryGetPropertyValue(name, out JsonNode? child) ? child : null; + if (index is { } i) + { + current = current is JsonArray a && i < a.Count ? a[i] : null; + } + + if (current is null) + { + return false; + } + } + + return true; + } + catch (Exception ex) when (ex is JsonException or IOException or ArgumentException) + { + return false; + } + } + private static void SetPath(JsonObject root, string path, JsonNode? value) { string[] segments = path.Split('.', StringSplitOptions.RemoveEmptyEntries); @@ -70,19 +168,17 @@ public static class ConfigWriter throw new ArgumentException($"Percorso vuoto.", nameof(path)); } - // Un JsonNode può appartenere a un solo albero: assegnarne uno che ne ha già - // uno solleva «The node already has a parent». Succede sistematicamente qui, - // perché la pagina delle impostazioni applica lo stesso lotto di modifiche due - // volte — prima a una copia temporanea per validarlo, poi al file vero. Clonare - // rende l'insieme delle modifiche riutilizzabile, che è come un chiamante si - // aspetta che si comporti. + // A JsonNode can belong to one tree only: assigning one that already has a parent + // throws «The node already has a parent». The settings page applies the same batch + // twice — to a temporary copy to validate it, then to the real file — so the value + // is cloned and the batch stays reusable. value = value?.DeepClone(); JsonNode current = root; for (int i = 0; i < segments.Length - 1; i++) { - current = Descend(current, segments[i], path); + current = Descend(current, segments[i], path, create: true)!; } (string name, int? index) = Parse(segments[^1]); @@ -108,15 +204,46 @@ public static class ConfigWriter target[name] = value; } - private static JsonNode Descend(JsonNode current, string segment, string path) + private static void DeletePath(JsonObject root, string path) + { + string[] segments = path.Split('.', StringSplitOptions.RemoveEmptyEntries); + if (segments.Length == 0) + { + return; + } + + JsonNode? current = root; + for (int i = 0; i < segments.Length - 1 && current is not null; i++) + { + current = Descend(current, segments[i], path, create: false); + } + + (string name, int? index) = Parse(segments[^1]); + if (index is null && current is JsonObject target) + { + target.Remove(name); + } + } + + private static JsonNode? Descend(JsonNode current, string segment, string path, bool create) { (string name, int? index) = Parse(segment); if (index is { } arrayIndex) { + if (!create && (current is not JsonObject o || o[name] is not JsonArray)) + { + return null; + } + JsonArray array = Array(current, name, path); if (arrayIndex >= array.Count) { + if (!create) + { + return null; + } + throw new InvalidOperationException( $"'{path}': l'elemento {arrayIndex} non esiste in '{name}'."); } @@ -127,11 +254,21 @@ public static class ConfigWriter if (current is not JsonObject parent) { + if (!create) + { + return null; + } + throw new InvalidOperationException($"'{path}': '{name}' non è dentro un oggetto."); } if (parent[name] is not JsonObject child) { + if (!create) + { + return null; + } + child = []; parent[name] = child; } @@ -150,7 +287,7 @@ public static class ConfigWriter ?? throw new InvalidOperationException($"'{path}': '{name}' non è un array."); } - /// Splits symbols[0] into its name and index. + /// Splits baskets[0] into its name and index. private static (string Name, int? Index) Parse(string segment) { int bracket = segment.IndexOf('[', StringComparison.Ordinal); @@ -184,14 +321,26 @@ public static class ConfigWriter edit(root); - string temporary = path + ".tmp"; + // A unique temporary name: two saves racing each other (the settings page and the + // import at startup never do, but a second process might) cannot share a .tmp. + string temporary = $"{path}.{Guid.NewGuid():N}.tmp"; - using (FileStream stream = File.Create(temporary)) - using (Utf8JsonWriter writer = new(stream, WriteOptions)) + try { - root.WriteTo(writer); - } + using (FileStream stream = File.Create(temporary)) + using (Utf8JsonWriter writer = new(stream, WriteOptions)) + { + root.WriteTo(writer); + } - File.Move(temporary, path, overwrite: true); + File.Move(temporary, path, overwrite: true); + } + finally + { + if (File.Exists(temporary)) + { + File.Delete(temporary); + } + } } } diff --git a/Encelado/src/Encelado.Engine/Configuration/EnvironmentImport.cs b/Encelado/src/Encelado.Engine/Configuration/EnvironmentImport.cs new file mode 100644 index 0000000..864d317 --- /dev/null +++ b/Encelado/src/Encelado.Engine/Configuration/EnvironmentImport.cs @@ -0,0 +1,358 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Nodes; +using Encelado.Core.Baskets; + +namespace Encelado.Engine.Configuration; + +/// What the import did at this start, for the log, the settings page and the diagnostics. +public sealed record ImportOutcome(bool Ran, bool Deferred, IReadOnlyList Imported, IReadOnlyList Ignored, IReadOnlyList Notes, bool ConfigChanged) +{ + public static readonly ImportOutcome Nothing = new(false, false, [], [], [], false); + + /// The notes on one line (empty when there is nothing to say). + public string Note => string.Join(" · ", Notes); +} + +/// +/// The one-time move of a 5.0 container's variables into the 5.1 places (decision C4). +/// Since 5.1 the only variable the container needs is the interface password: everything +/// else is set from the interface. A container upgraded from 5.0 still carries the old +/// variables in its Unraid definition until the owner edits it, and this makes that +/// harmless: +/// +/// secrets go into the encrypted store, only into empty slots and only when the store is open: +/// ETORO_API_KEY/ETORO_USER_KEY into the account the old mode/environment pair +/// meant (the merge rule), the old etoro.keys.enc (with ENCELADO_KEY_PASSPHRASE) +/// for both accounts — then renamed .migrato —, TELEGRAM_BOT_TOKEN, and the keys a +/// 5.0 file may carry; +/// settings go into encelado.json only when the variable differs from the factory +/// default and the file still holds the factory default (a template default such as +/// USD or Demo is not an intent): TELEGRAM_CHAT_ID (when the chat id is empty), +/// ENCELADO_DISPLAY_CURRENCY, ENCELADO_LOG_LEVEL, +/// ENCELADO_EXECUTION_MODE+ETORO_ENVIRONMENT, ENCELADO_AUTOSTART=0; +/// TZ and ENCELADO_CONFIRM_LIVE are never imported. +/// +/// 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 +/// ignored and listed at every start, "puoi toglierla dal container". +/// +public static class EnvironmentImport +{ + public const string MarkerFileName = "import-5.1.json"; + + /// The variables of 5.0 that 5.1 no longer reads (the password's own alias is handled by ). + public static readonly IReadOnlyList LegacyVariables = + [ + "ETORO_API_KEY", + "ETORO_USER_KEY", + "ETORO_ENVIRONMENT", + "ENCELADO_EXECUTION_MODE", + "ENCELADO_KEY_PASSPHRASE", + "ENCELADO_CONFIRM_LIVE", + "ENCELADO_AUTOSTART", + "ENCELADO_DISPLAY_CURRENCY", + "ENCELADO_LOG_LEVEL", + "ENCELADO_TIME_ZONE", + "TELEGRAM_BOT_TOKEN", + "TELEGRAM_CHAT_ID", + ]; + + private static readonly string[] LogLevels = ["trace", "debug", "info", "warn", "error", "none"]; + + /// The legacy variables set (non-empty) in . + public static IReadOnlyList Present(Func environment) + { + ArgumentNullException.ThrowIfNull(environment); + return [.. LegacyVariables.Where(v => !string.IsNullOrWhiteSpace(environment(v)))]; + } + + public static ImportOutcome Run(string configPath, SecretStore store, Func environment, DateTime nowUtc) + { + ArgumentException.ThrowIfNullOrWhiteSpace(configPath); + ArgumentNullException.ThrowIfNull(store); + ArgumentNullException.ThrowIfNull(environment); + + IReadOnlyList present = Present(environment); + string directory = Path.GetDirectoryName(Path.GetFullPath(configPath)) ?? "."; + string marker = Path.Combine(directory, MarkerFileName); + if (File.Exists(marker)) + { + return new ImportOutcome(false, false, [], present, ReadNotes(marker), false); + } + + List imported = []; + List notes = []; + bool deferred = false; + + string? Env(string name) => environment(name) is { } v && v.Trim().Length > 0 ? v.Trim() : null; + + (string? fileModeRaw, string? fileEnvironmentRaw) = ConfigLoader.ReadRawModeAndEnvironment(configPath); + string? envMode = Env("ENCELADO_EXECUTION_MODE"); + string? envEnvironment = Env("ETORO_ENVIRONMENT"); + + // -------------------------------------------------------------- secrets + List secretDeletions = []; + if (store.State == SecretStoreState.Locked) + { + deferred = true; + notes.Add("segreti bloccati: l'importazione delle chiavi è rimandata al prossimo avvio (sblocca o ricomincia da Impostazioni)"); + } + else + { + ImportLegacyKeyFile(directory, store, Env(KeyStores.PassphraseVariable), imported, notes); + + // The keys of the environment belong to the account 5.0 used them on. + bool envDemo = !MergedMode(envMode ?? fileModeRaw, envEnvironment ?? fileEnvironmentRaw, out _).IsLive(); + string? api = KeyStores.Clean(Env("ETORO_API_KEY")); + string? user = KeyStores.Clean(Env("ETORO_USER_KEY")); + if (api is not null && user is not null) + { + if (TryImport(store, envDemo, new EtoroKeys(api, user, nowUtc), "ETORO_API_KEY/ETORO_USER_KEY", notes)) + { + imported.Add("ETORO_API_KEY"); + imported.Add("ETORO_USER_KEY"); + } + } + else if (api is not null || user is not null) + { + notes.Add("ETORO_API_KEY e ETORO_USER_KEY vanno insieme: con una sola delle due non è stato importato niente"); + } + + LegacyFileSecrets fileSecrets = ConfigLoader.ReadLegacySecrets(configPath); + if (fileSecrets.HasEtoroKeys) + { + bool fileDemo = !MergedMode(fileModeRaw, fileEnvironmentRaw, out _).IsLive(); + if (TryImport(store, fileDemo, new EtoroKeys(fileSecrets.ApiKey, fileSecrets.UserKey, nowUtc), "le chiavi scritte in encelado.json", notes)) + { + imported.Add("etoro.apiKey/userKey (file)"); + } + } + + string? telegram = Env("TELEGRAM_BOT_TOKEN") ?? (fileSecrets.TelegramToken.Length > 0 ? fileSecrets.TelegramToken : null); + if (telegram is not null) + { + if (store.TelegramToken.Length == 0) + { + store.SaveTelegramToken(telegram); + imported.Add(Env("TELEGRAM_BOT_TOKEN") is not null ? "TELEGRAM_BOT_TOKEN" : "notifications.telegram.botToken (file)"); + } + else + { + notes.Add("token Telegram già nel deposito: quello dell'ambiente o del file è ignorato"); + } + } + + // Plaintext secrets leave the main file once they are in the store; the overlay is + // the operator's own file, which the program never writes: it is only reported. + secretDeletions.AddRange(ConfigLoader.SecretKeys.Where(k => ConfigWriter.Contains(configPath, k))); + string overlayPath = ConfigLoader.LocalPath(configPath); + if (ConfigLoader.SecretKeys.Any(k => ConfigWriter.Contains(overlayPath, k))) + { + notes.Add($"{Path.GetFileName(overlayPath)} contiene ancora segreti in chiaro: ora sono nel deposito cifrato, toglili dal file"); + } + } + + // -------------------------------------------------------------- settings + Dictionary changes = new(StringComparer.Ordinal); + bool configChanged = false; + if (File.Exists(configPath)) + { + BotConfig file = ConfigLoader.Load(configPath, out _); + + if (Env("TELEGRAM_CHAT_ID") is { } chat && file.Notifications.Telegram.ChatId.Length == 0) + { + changes["notifications.telegram.chatId"] = JsonValue.Create(chat); + imported.Add("TELEGRAM_CHAT_ID"); + } + + if (Env("ENCELADO_DISPLAY_CURRENCY") is { } currency) + { + string c = currency.ToUpperInvariant(); + if (!UiOptions.Currencies.Contains(c)) + { + notes.Add($"ENCELADO_DISPLAY_CURRENCY '{currency}' non è una valuta ammessa: ignorata"); + } + else if (c != "USD" && file.Ui.DisplayCurrency.Equals("USD", StringComparison.OrdinalIgnoreCase)) + { + changes["ui.displayCurrency"] = JsonValue.Create(c); + imported.Add("ENCELADO_DISPLAY_CURRENCY"); + } + } + + if (Env("ENCELADO_LOG_LEVEL") is { } level) + { + string l = level.ToLowerInvariant() switch { "warning" => "warn", "information" => "info", "verbose" => "trace", "off" => "none", var x => x }; + if (!LogLevels.Contains(l)) + { + notes.Add($"ENCELADO_LOG_LEVEL '{level}' non è un livello ammesso: ignorata"); + } + else if (l != "info" && file.Logging.Level.Equals("info", StringComparison.OrdinalIgnoreCase)) + { + changes["logging.level"] = JsonValue.Create(l); + imported.Add("ENCELADO_LOG_LEVEL"); + } + } + + if (Env("ENCELADO_AUTOSTART")?.ToLowerInvariant() is "0" or "false" && file.Run.Autostart) + { + changes["run.autostart"] = JsonValue.Create(false); + imported.Add("ENCELADO_AUTOSTART"); + } + + if (envMode is not null || envEnvironment is not null) + { + ExecutionMode merged = MergedMode(envMode ?? fileModeRaw, envEnvironment ?? fileEnvironmentRaw, out bool disagree); + if (disagree) + { + notes.Add($"ENCELADO_EXECUTION_MODE '{envMode ?? fileModeRaw ?? "Demo"}' ed ETORO_ENVIRONMENT '{envEnvironment ?? fileEnvironmentRaw ?? "demo"}' non erano d'accordo: vale {merged} (dalla 5.1 la modalità sceglie anche il conto)"); + } + + if (merged.IsLive() && !file.Run.Mode.IsLive()) + { + if (file.Run.AllowLive) + { + changes["run.executionMode"] = JsonValue.Create(merged.ToString()); + imported.Add("ENCELADO_EXECUTION_MODE"); + notes.Add("modalità Live importata: il motore non parte da solo, serve AVVIA con la frase CONFERMO LIVE"); + } + else + { + notes.Add("modalità Live non importata: «Consenti il conto reale» (run.allowLive) è spento"); + } + } + } + + if (changes.Count > 0 || secretDeletions.Count > 0) + { + List deletions = [.. secretDeletions, .. ConfigLoader.ObsoleteKeys.Where(k => ConfigWriter.Contains(configPath, k))]; + ConfigWriter.Apply(configPath, Settings.SettingsService.WithDocumentation(configPath, ConfigDefaults.Json, changes), deletions); + configChanged = true; + } + } + + if (!deferred) + { + WriteMarker(marker, nowUtc, imported, present, notes); + } + + return new ImportOutcome(true, deferred, imported, present, notes, configChanged); + } + + private static ExecutionMode MergedMode(string? mode, string? environment, out bool disagree) + { + ExecutionModeExtensions.TryParse(mode ?? "Demo", out ExecutionMode parsed); + return ExecutionModeExtensions.Merge(parsed, environment ?? "demo", out disagree); + } + + private static void ImportLegacyKeyFile(string directory, SecretStore store, string? passphrase, List imported, List notes) + { + string path = Path.Combine(directory, KeyStores.FileName); + if (!File.Exists(path)) + { + return; + } + + if (passphrase is null) + { + notes.Add($"{KeyStores.FileName} della 5.0 non è leggibile senza {KeyStores.PassphraseVariable}: reinserisci le chiavi da Impostazioni ▸ Conto (il file resta dov'è)"); + return; + } + + EncryptedFileKeyStore old = new(path, passphrase); + EtoroKeys? demo = old.Load(demo: true); + EtoroKeys? real = old.Load(demo: false); + if (demo is null && real is null) + { + notes.Add($"{KeyStores.PassphraseVariable} non apre {KeyStores.FileName} (o il file è vuoto): reinserisci le chiavi da Impostazioni ▸ Conto"); + return; + } + + if (demo is not null) + { + TryImport(store, true, demo, $"{KeyStores.FileName} (conto demo)", notes); + } + + if (real is not null) + { + TryImport(store, false, real, $"{KeyStores.FileName} (conto reale)", notes); + } + + try + { + File.Move(path, path + ".migrato", overwrite: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + notes.Add($"{KeyStores.FileName} importato ma non rinominato: {ex.Message}"); + } + + imported.Add(KeyStores.FileName); + } + + /// Stores only into an empty slot; says so when the slot was taken. + private static bool TryImport(SecretStore store, bool demo, EtoroKeys keys, string from, List notes) + { + if (store.Etoro(demo) is not null) + { + notes.Add($"chiavi del conto {(demo ? "demo" : "reale")} già nel deposito: {from} ignorate"); + return false; + } + + store.SaveEtoro(demo, keys); + notes.Add($"chiavi del conto {(demo ? "demo" : "reale")} importate da {from} ({KeyStores.Mask(keys.ApiKey)})"); + return true; + } + + private static void WriteMarker(string path, DateTime nowUtc, List imported, IReadOnlyList present, List notes) + { + try + { + using MemoryStream ms = new(); + using (Utf8JsonWriter w = new(ms, new JsonWriterOptions { Indented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping })) + { + w.WriteStartObject(); + w.WriteString("_commento", "Importazione una tantum delle variabili d'ambiente della 5.0 (Encelado 5.1). Finché questo file esiste non viene ripetuta; le variabili ancora presenti sono ignorate."); + w.WriteString("utc", nowUtc.ToString("O", CultureInfo.InvariantCulture)); + w.WriteString("version", "5.1"); + Array(w, "imported", imported); + Array(w, "presentAtImport", present); + Array(w, "notes", notes); + w.WriteEndObject(); + } + + File.WriteAllBytes(path + ".tmp", ms.ToArray()); + File.Move(path + ".tmp", path, overwrite: true); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + notes.Add($"{MarkerFileName} non scritto ({ex.Message}): l'importazione verrà ripetuta, senza effetti, al prossimo avvio"); + } + + static void Array(Utf8JsonWriter w, string name, IEnumerable items) + { + w.WriteStartArray(name); + foreach (string i in items) + { + w.WriteStringValue(i); + } + + w.WriteEndArray(); + } + } + + private static List ReadNotes(string path) + { + try + { + using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path)); + return doc.RootElement.TryGetProperty("notes", out JsonElement notes) && notes.ValueKind == JsonValueKind.Array + ? [.. notes.EnumerateArray().Where(static n => n.ValueKind == JsonValueKind.String).Select(static n => n.GetString() ?? string.Empty)] + : []; + } + catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException) + { + return []; + } + } +} diff --git a/Encelado/src/Encelado.Engine/Configuration/InterfacePassword.cs b/Encelado/src/Encelado.Engine/Configuration/InterfacePassword.cs new file mode 100644 index 0000000..6c1fd79 --- /dev/null +++ b/Encelado/src/Encelado.Engine/Configuration/InterfacePassword.cs @@ -0,0 +1,54 @@ +namespace Encelado.Engine.Configuration; + +/// +/// The interface password (5.1, decision C1): the one secret the container's environment +/// carries. ENCELADO_PASSWORD ("Password interfaccia" in the Unraid template); +/// ENCELADO_WEB_TOKEN, its name in 5.0, still works as a deprecated alias, and when +/// both are set and differ ENCELADO_PASSWORD wins. Without a password the server +/// listens on localhost only and asks for nothing (development). +/// +/// Read once, by the program, and passed down: nothing else reads the environment, so the +/// tests never have to change the process's variables. +/// +/// +public sealed record InterfacePassword(string Value, string Source, IReadOnlyList Warnings) +{ + public const string Variable = "ENCELADO_PASSWORD"; + + public const string LegacyVariable = "ENCELADO_WEB_TOKEN"; + + /// The source when no password is set. + public const string NoSource = "none"; + + public static readonly InterfacePassword None = new(string.Empty, NoSource, []); + + public bool IsSet => Value.Length > 0; + + public static InterfacePassword Resolve(Func environment) + { + ArgumentNullException.ThrowIfNull(environment); + string password = environment(Variable)?.Trim() ?? string.Empty; + string legacy = environment(LegacyVariable)?.Trim() ?? string.Empty; + + if (password.Length > 0) + { + List warnings = []; + if (legacy.Length > 0) + { + warnings.Add(legacy == password + ? $"{LegacyVariable} è il nome della 5.0 della password: vale {Variable}, puoi togliere {LegacyVariable} dal container" + : $"{LegacyVariable} è diversa da {Variable}: vale {Variable}; togli {LegacyVariable} dal container"); + } + + return new InterfacePassword(password, Variable, warnings); + } + + if (legacy.Length > 0) + { + return new InterfacePassword(legacy, LegacyVariable, + [$"{LegacyVariable} è deprecata: rinominala {Variable} nel container (stesso valore, così i segreti cifrati restano leggibili)"]); + } + + return None; + } +} diff --git a/Encelado/src/Encelado.Engine/Configuration/KeyStore.cs b/Encelado/src/Encelado.Engine/Configuration/KeyStore.cs index b5b51d2..def8761 100644 --- a/Encelado/src/Encelado.Engine/Configuration/KeyStore.cs +++ b/Encelado/src/Encelado.Engine/Configuration/KeyStore.cs @@ -6,40 +6,22 @@ using System.Text.Json; namespace Encelado.Engine.Configuration; -/// The two long-lived keys eToro issues, for one environment. +/// The two long-lived keys eToro issues, for one account. public sealed record EtoroKeys(string ApiKey, string UserKey, DateTime SavedUtc) { public bool IsComplete => ApiKey.Length > 0 && UserKey.Length > 0; } /// -/// Where the eToro keys come from (§12 of the 5.0 plan). Two implementations: the -/// environment (ETORO_API_KEY/ETORO_USER_KEY, the default in the -/// container, read-only) and a file encrypted with AES-256-GCM under a passphrase from -/// ENCELADO_KEY_PASSPHRASE, kept in the configuration folder. DPAPI went with -/// the Windows desktop (ADR-0007): the bot runs in a Linux container. +/// The key file of 5.0 (etoro.keys.enc, format ENC1): AES-256-GCM under a +/// passphrase from ENCELADO_KEY_PASSPHRASE, PBKDF2-SHA256 with a fresh salt at every +/// write; a magic, the salt, the nonce, the tag and the ciphertext of a small JSON with +/// one entry per account. Since 5.1 the keys live in : this +/// class is only read by the one-time import (), which then +/// renames the file .migrato; writing is kept for the tests that build such a file. +/// A wrong passphrase or a damaged file reads as "no keys", never as a crash. /// -public interface IKeyStore -{ - /// One line for the settings page: where the keys are and whether they can be written. - string Description { get; } - - bool CanSave { get; } - - EtoroKeys? Load(bool demo); - - void Save(bool demo, EtoroKeys keys); - - bool Clear(bool demo); -} - -/// -/// A file encrypted with AES-256-GCM. The key is derived from the passphrase with -/// PBKDF2-SHA256 (a fresh salt at every write); the file carries a magic, the salt, -/// the nonce, the tag and the ciphertext of a small JSON with one entry per -/// environment. A wrong passphrase or a damaged file reads as "no keys", never as a crash. -/// -public sealed class EncryptedFileKeyStore(string path, string passphrase) : IKeyStore +public sealed class EncryptedFileKeyStore(string path, string passphrase) { private static readonly byte[] Magic = "ENC1"u8.ToArray(); private const int SaltSize = 16; @@ -49,8 +31,6 @@ public sealed class EncryptedFileKeyStore(string path, string passphrase) : IKey public string Path { get; } = path ?? throw new ArgumentNullException(nameof(path)); - public string Description => $"file cifrato {Path} (AES-256-GCM, passphrase da ENCELADO_KEY_PASSPHRASE)"; - public bool CanSave => passphrase.Length > 0; public bool Exists => File.Exists(Path); @@ -242,48 +222,15 @@ public sealed class EncryptedFileKeyStore(string path, string passphrase) : IKey Rfc2898DeriveBytes.Pbkdf2(Encoding.UTF8.GetBytes(passphrase), salt, Iterations, HashAlgorithmName.SHA256, 32); } -/// Builds the store the environment allows and installs the keys into the configuration. +/// Names of the 5.0 key file, and the helpers every key passes through: cleaning a pasted key, masking a stored one. public static class KeyStores { + /// The passphrase variable of 5.0: read once by the import to decrypt , then ignored. public const string PassphraseVariable = "ENCELADO_KEY_PASSPHRASE"; + /// The key file of 5.0 in the configuration folder. public const string FileName = "etoro.keys.enc"; - /// The encrypted file store of this configuration folder (writable only with a passphrase in the environment). - public static EncryptedFileKeyStore File(BotConfig config) - { - ArgumentNullException.ThrowIfNull(config); - return new EncryptedFileKeyStore(Path.Combine(config.Run.BaseDirectory, FileName), Environment.GetEnvironmentVariable(PassphraseVariable)?.Trim() ?? string.Empty); - } - - /// - /// Installs keys into the configuration: from the environment first (already - /// applied by the loader), then from the encrypted file. Returns whether a pair was found. - /// - public static bool Resolve(BotConfig config, out string origin) - { - ArgumentNullException.ThrowIfNull(config); - if (config.Etoro.HasKeys) - { - origin = $"variabili d'ambiente ({Mask(config.Etoro.ApiKey)})"; - return true; - } - - EncryptedFileKeyStore store = File(config); - if (store.Load(config.Etoro.IsDemo) is { IsComplete: true } saved) - { - config.Etoro.ApiKey = saved.ApiKey; - config.Etoro.UserKey = saved.UserKey; - origin = $"file cifrato ({Mask(saved.ApiKey)}, {saved.SavedUtc:yyyy-MM-dd})"; - return true; - } - - origin = store.Exists && !store.CanSave - ? $"nessuna chiave eToro: esiste {store.Path} ma manca {PassphraseVariable} per leggerlo" - : "nessuna chiave eToro"; - return false; - } - /// /// Strips control characters, byte-order marks and stray spacing from a pasted key. /// Keys copied out of a browser routinely carry a zero-width space, which would diff --git a/Encelado/src/Encelado.Engine/Configuration/SecretStore.cs b/Encelado/src/Encelado.Engine/Configuration/SecretStore.cs new file mode 100644 index 0000000..7f85461 --- /dev/null +++ b/Encelado/src/Encelado.Engine/Configuration/SecretStore.cs @@ -0,0 +1,659 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; + +namespace Encelado.Engine.Configuration; + +/// What the secret store can do right now. +public enum SecretStoreState +{ + /// No secrets.enc yet: nothing saved. The first save creates it. + Empty = 0, + + /// The file is open with the interface password. + Open, + + /// + /// The file exists but cannot be opened: it was encrypted with another password (the + /// password changed), the local key is missing, or the file is damaged. Nothing can be + /// read or saved until it is unlocked with the previous password or reset. + /// + Locked, + + /// Open with a random key kept in secrets.key: no interface password (development on localhost). + LocalKey, +} + +/// One secret as the settings page shows it: whether it is there, its first characters, when it was saved. +public sealed record SecretInfo(bool Present, string Masked, DateTime? SavedUtc) +{ + public static readonly SecretInfo None = new(false, string.Empty, null); +} + +/// +/// The only place the secrets live (5.1, decision C3): <config>/secrets.enc +/// holds the eToro keys of the demo and of the real account and the Telegram bot +/// token, encrypted with AES-256-GCM. +/// +/// The key comes from the interface password (ENCELADO_PASSWORD) through +/// PBKDF2-SHA256 with 600 000 iterations; the salt is kept across rewrites and the nonce +/// is fresh at every write, so the key is derived once per process. Without a password +/// (development on localhost) the key is 32 random bytes in secrets.key; when a +/// password appears, the file is decrypted with that key, encrypted again with the +/// password and the key file is deleted. +/// +/// +/// Layout: ENC2 | key source (1 password, 2 local key) | PBKDF2 iterations (int32, +/// little endian) | salt 16 | nonce 12 | tag 16 | ciphertext. The header is authenticated +/// with the ciphertext. Writes are atomic and the file is readable by its owner only. +/// A changed password leaves the store : the web +/// login still works (it uses the variable), and the settings page offers to unlock with +/// the previous password or to start again with an empty store (the old file stays as a +/// .bak). Secrets never enter the shared configuration: callers take a private copy. +/// +/// +public sealed class SecretStore +{ + public const string FileName = "secrets.enc"; + + public const string LocalKeyFileName = "secrets.key"; + + public const int DefaultIterations = 600_000; + + private static readonly byte[] Magic = "ENC2"u8.ToArray(); + private const byte SourcePassword = 1; + private const byte SourceLocalKey = 2; + private const int SaltSize = 16; + private const int NonceSize = 12; + private const int TagSize = 16; + private const int KeySize = 32; + private const int HeaderSize = 4 + 1 + 4 + SaltSize; + + private readonly Lock _gate = new(); + private readonly string _password; + private readonly int _iterations; + private Payload _payload = new(); + private byte[]? _key; + private byte[] _salt = []; + private byte _source; + private int _fileIterations; + private SecretStoreState _state; + private string _problem = string.Empty; + + /// The configuration folder (/config in the container). + /// The interface password; empty for the local-key mode. + /// PBKDF2 iterations for a new file (the tests use fewer; the file records its own). + public SecretStore(string directory, string password, int iterations = DefaultIterations) + { + ArgumentException.ThrowIfNullOrWhiteSpace(directory); + Directory = directory; + FilePath = System.IO.Path.Combine(directory, FileName); + KeyPath = System.IO.Path.Combine(directory, LocalKeyFileName); + _password = password ?? string.Empty; + _iterations = Math.Max(1, iterations); + lock (_gate) + { + LoadLocked(); + } + } + + public string Directory { get; } + + public string FilePath { get; } + + public string KeyPath { get; } + + /// Whether an interface password protects the store (otherwise the local key does). + public bool HasPassword => _password.Length > 0; + + public SecretStoreState State + { + get + { + lock (_gate) + { + return _state; + } + } + } + + /// The state as the API spells it: open, empty, locked, localKey. + public string StateName => State switch + { + SecretStoreState.Open => "open", + SecretStoreState.Locked => "locked", + SecretStoreState.LocalKey => "localKey", + _ => "empty", + }; + + /// Why the store is locked, in words for the settings page; empty otherwise. + public string Problem + { + get + { + lock (_gate) + { + return _problem; + } + } + } + + /// What happened when the store was opened (the migration from the local key to the password), for the log; null when nothing. + public string? OpenNote { get; private set; } + + // ----------------------------------------------------------------------- + // Reading + // ----------------------------------------------------------------------- + + /// The keys of one account, or null when none are saved (or the store is locked). + public EtoroKeys? Etoro(bool demo) + { + lock (_gate) + { + return _state is SecretStoreState.Open or SecretStoreState.LocalKey && _payload.Etoro.TryGetValue(Account(demo), out EtoroKeys? keys) && keys.IsComplete ? keys : null; + } + } + + /// The Telegram bot token, or empty. + public string TelegramToken + { + get + { + lock (_gate) + { + return _state is SecretStoreState.Open or SecretStoreState.LocalKey ? _payload.TelegramToken : string.Empty; + } + } + } + + public SecretInfo DescribeEtoro(bool demo) + { + EtoroKeys? keys = Etoro(demo); + return keys is null ? SecretInfo.None : new SecretInfo(true, KeyStores.Mask(keys.ApiKey), keys.SavedUtc == DateTime.MinValue ? null : keys.SavedUtc); + } + + public SecretInfo DescribeTelegram() + { + lock (_gate) + { + return _state is SecretStoreState.Open or SecretStoreState.LocalKey && _payload.TelegramToken.Length > 0 + ? new SecretInfo(true, KeyStores.Mask(_payload.TelegramToken), _payload.TelegramSavedUtc) + : SecretInfo.None; + } + } + + // ----------------------------------------------------------------------- + // Writing + // ----------------------------------------------------------------------- + + public void SaveEtoro(bool demo, EtoroKeys keys) + { + ArgumentNullException.ThrowIfNull(keys); + if (!keys.IsComplete) + { + throw new ArgumentException("servono entrambe le chiavi (x-api-key e x-user-key)", nameof(keys)); + } + + lock (_gate) + { + EnsureWritable(); + _payload.Etoro[Account(demo)] = keys; + WriteLocked(); + } + } + + /// Removes the keys of one account; false when there were none. + public bool ClearEtoro(bool demo) + { + lock (_gate) + { + EnsureWritable(); + if (!_payload.Etoro.Remove(Account(demo))) + { + return false; + } + + WriteLocked(); + return true; + } + } + + public void SaveTelegramToken(string token) + { + ArgumentException.ThrowIfNullOrWhiteSpace(token); + lock (_gate) + { + EnsureWritable(); + _payload.TelegramToken = token.Trim(); + _payload.TelegramSavedUtc = DateTime.UtcNow; + WriteLocked(); + } + } + + /// Removes the Telegram token; false when there was none. + public bool ClearTelegramToken() + { + lock (_gate) + { + EnsureWritable(); + if (_payload.TelegramToken.Length == 0) + { + return false; + } + + _payload.TelegramToken = string.Empty; + _payload.TelegramSavedUtc = null; + WriteLocked(); + return true; + } + } + + /// + /// Opens a store locked by a password change: decrypts with + /// and encrypts again with the current password (or the local key without one). Returns + /// false, with the reason, when the previous password does not open it either. + /// + public bool Unlock(string previousPassword, out string message) + { + lock (_gate) + { + if (_state != SecretStoreState.Locked) + { + message = "il deposito dei segreti non è bloccato"; + return false; + } + + if (string.IsNullOrEmpty(previousPassword)) + { + message = "serve la password precedente"; + return false; + } + + if (!TryReadFile(out byte[] raw, out byte source, out int iterations, out byte[] salt) || source != SourcePassword) + { + message = source == SourceLocalKey + ? "il deposito è cifrato con la chiave locale (secrets.key), che non c'è più: solo «ricomincia» lo rimette in uso" + : "il file dei segreti è danneggiato: solo «ricomincia» lo rimette in uso"; + return false; + } + + byte[] oldKey = DeriveKey(previousPassword, salt, iterations); + try + { + if (!TryDecrypt(raw, oldKey, out Payload payload)) + { + message = "la password precedente non apre il deposito dei segreti"; + return false; + } + + _payload = payload; + } + finally + { + CryptographicOperations.ZeroMemory(oldKey); + } + + // Encrypted again with what is in force now. + _key = null; + _state = SecretStoreState.Empty; + PrepareNewKey(); + WriteLocked(); + _problem = string.Empty; + message = HasPassword ? "segreti sbloccati e cifrati con la password attuale" : "segreti sbloccati e cifrati con la chiave locale"; + return true; + } + } + + /// + /// Starts again with an empty store: the current file (and the local key, if any) is + /// renamed with the date and .bak, never deleted. Returns the backup path, or + /// null when there was no file. + /// + public string? Reset() + { + lock (_gate) + { + string stamp = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture); + string? backup = null; + if (File.Exists(FilePath)) + { + backup = $"{FilePath}.{stamp}.bak"; + File.Move(FilePath, backup, overwrite: true); + } + + if (File.Exists(KeyPath)) + { + File.Move(KeyPath, $"{KeyPath}.{stamp}.bak", overwrite: true); + } + + _payload = new Payload(); + _key = null; + _salt = []; + _state = SecretStoreState.Empty; + _problem = string.Empty; + return backup; + } + } + + // ----------------------------------------------------------------------- + // The file + // ----------------------------------------------------------------------- + + private static string Account(bool demo) => demo ? "demo" : "real"; + + private void EnsureWritable() + { + if (_state == SecretStoreState.Locked) + { + throw new InvalidOperationException($"deposito dei segreti bloccato ({_problem}): sbloccalo con la password precedente o ricomincia da Impostazioni"); + } + + if (_key is null) + { + PrepareNewKey(); + } + } + + /// A key for a store that has none yet: from the password (new salt), or a new local key file. + private void PrepareNewKey() + { + if (HasPassword) + { + _source = SourcePassword; + _fileIterations = _iterations; + _salt = RandomNumberGenerator.GetBytes(SaltSize); + _key = DeriveKey(_password, _salt, _fileIterations); + return; + } + + _source = SourceLocalKey; + _fileIterations = 0; + _salt = new byte[SaltSize]; + _key = RandomNumberGenerator.GetBytes(KeySize); + WriteAtomically(KeyPath, _key); + } + + private void LoadLocked() + { + _payload = new Payload(); + _key = null; + _problem = string.Empty; + if (!File.Exists(FilePath)) + { + _state = SecretStoreState.Empty; + return; + } + + if (!TryReadFile(out byte[] raw, out byte source, out int iterations, out byte[] salt)) + { + Lock("il file secrets.enc non è leggibile o è danneggiato"); + return; + } + + if (source == SourcePassword) + { + if (!HasPassword) + { + Lock("i segreti sono cifrati con una password dell'interfaccia, ma ora non ce n'è nessuna"); + return; + } + + byte[] key = DeriveKey(_password, salt, iterations); + if (!TryDecrypt(raw, key, out Payload payload)) + { + CryptographicOperations.ZeroMemory(key); + Lock("i segreti sono cifrati con un'altra password dell'interfaccia"); + return; + } + + _payload = payload; + _key = key; + _salt = salt; + _source = SourcePassword; + _fileIterations = iterations; + _state = SecretStoreState.Open; + return; + } + + // Local key. + byte[]? localKey = ReadLocalKey(); + if (localKey is null) + { + Lock("i segreti sono cifrati con la chiave locale secrets.key, che manca o è danneggiata"); + return; + } + + if (!TryDecrypt(raw, localKey, out Payload local)) + { + Lock("la chiave locale secrets.key non apre i segreti"); + return; + } + + _payload = local; + if (!HasPassword) + { + _key = localKey; + _salt = salt; + _source = SourceLocalKey; + _fileIterations = 0; + _state = SecretStoreState.LocalKey; + return; + } + + // A password appeared: the store moves under it and the local key goes. + CryptographicOperations.ZeroMemory(localKey); + _state = SecretStoreState.Empty; + PrepareNewKey(); + WriteLocked(); + try + { + File.Delete(KeyPath); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // The store no longer needs it; a leftover is harmless. + } + + OpenNote = "segreti cifrati di nuovo con la password dell'interfaccia; la chiave locale secrets.key è stata eliminata"; + } + + private void Lock(string why) + { + _state = SecretStoreState.Locked; + _problem = why; + } + + private byte[]? ReadLocalKey() + { + try + { + byte[] key = File.Exists(KeyPath) ? File.ReadAllBytes(KeyPath) : []; + return key.Length == KeySize ? key : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return null; + } + } + + private bool TryReadFile(out byte[] raw, out byte source, out int iterations, out byte[] salt) + { + source = 0; + iterations = 0; + salt = []; + try + { + raw = File.ReadAllBytes(FilePath); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + raw = []; + return false; + } + + if (raw.Length < HeaderSize + NonceSize + TagSize || !raw.AsSpan(0, Magic.Length).SequenceEqual(Magic)) + { + return false; + } + + source = raw[4]; + iterations = BinaryPrimitives.ReadInt32LittleEndian(raw.AsSpan(5, 4)); + salt = raw.AsSpan(9, SaltSize).ToArray(); + return source is SourcePassword or SourceLocalKey && (source == SourceLocalKey || iterations > 0); + } + + private static bool TryDecrypt(byte[] raw, byte[] key, out Payload payload) + { + payload = new Payload(); + ReadOnlySpan header = raw.AsSpan(0, HeaderSize); + ReadOnlySpan nonce = raw.AsSpan(HeaderSize, NonceSize); + ReadOnlySpan tag = raw.AsSpan(HeaderSize + NonceSize, TagSize); + ReadOnlySpan cipher = raw.AsSpan(HeaderSize + NonceSize + TagSize); + byte[] plaintext = new byte[cipher.Length]; + try + { + using AesGcm aes = new(key, TagSize); + aes.Decrypt(nonce, cipher, tag, plaintext, header); + payload = Payload.Parse(plaintext); + return true; + } + catch (Exception ex) when (ex is CryptographicException or ArgumentException or JsonException) + { + return false; + } + finally + { + CryptographicOperations.ZeroMemory(plaintext); + } + } + + private void WriteLocked() + { + if (_key is null) + { + PrepareNewKey(); + } + + byte[] plaintext = _payload.Serialize(); + byte[] file = new byte[HeaderSize + NonceSize + TagSize + plaintext.Length]; + Magic.CopyTo(file, 0); + file[4] = _source; + BinaryPrimitives.WriteInt32LittleEndian(file.AsSpan(5, 4), _fileIterations); + _salt.CopyTo(file, 9); + byte[] nonce = RandomNumberGenerator.GetBytes(NonceSize); + nonce.CopyTo(file, HeaderSize); + try + { + using AesGcm aes = new(_key!, TagSize); + aes.Encrypt(nonce, plaintext, file.AsSpan(HeaderSize + NonceSize + TagSize), file.AsSpan(HeaderSize + NonceSize, TagSize), file.AsSpan(0, HeaderSize)); + } + finally + { + CryptographicOperations.ZeroMemory(plaintext); + } + + WriteAtomically(FilePath, file); + _state = _source == SourcePassword ? SecretStoreState.Open : SecretStoreState.LocalKey; + } + + private static void WriteAtomically(string path, byte[] content) + { + string? dir = System.IO.Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(dir)) + { + System.IO.Directory.CreateDirectory(dir); + } + + string temporary = $"{path}.{Guid.NewGuid():N}.tmp"; + File.WriteAllBytes(temporary, content); + if (!OperatingSystem.IsWindows()) + { + try + { + File.SetUnixFileMode(temporary, UnixFileMode.UserRead | UnixFileMode.UserWrite); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or PlatformNotSupportedException) + { + // Best effort: the content is encrypted anyway. + } + } + + File.Move(temporary, path, overwrite: true); + } + + private static byte[] DeriveKey(string password, byte[] salt, int iterations) => + Rfc2898DeriveBytes.Pbkdf2(Encoding.UTF8.GetBytes(password), salt, iterations, HashAlgorithmName.SHA256, KeySize); + + /// The decrypted content: {"etoro":{"demo":{…},"real":{…}},"telegram":{"botToken","savedUtc"}}. + private sealed class Payload + { + public Dictionary Etoro { get; } = new(StringComparer.OrdinalIgnoreCase); + + public string TelegramToken { get; set; } = string.Empty; + + public DateTime? TelegramSavedUtc { get; set; } + + public byte[] Serialize() + { + ArrayBufferWriter buffer = new(512); + using (Utf8JsonWriter w = new(buffer)) + { + w.WriteStartObject(); + w.WriteStartObject("etoro"); + foreach ((string account, EtoroKeys k) in Etoro) + { + w.WriteStartObject(account); + w.WriteString("apiKey", k.ApiKey); + w.WriteString("userKey", k.UserKey); + w.WriteString("savedUtc", k.SavedUtc.ToString("O", CultureInfo.InvariantCulture)); + w.WriteEndObject(); + } + + w.WriteEndObject(); + w.WriteStartObject("telegram"); + w.WriteString("botToken", TelegramToken); + w.WriteString("savedUtc", TelegramSavedUtc?.ToString("O", CultureInfo.InvariantCulture) ?? string.Empty); + w.WriteEndObject(); + w.WriteEndObject(); + } + + return buffer.WrittenSpan.ToArray(); + } + + public static Payload Parse(byte[] json) + { + Payload p = new(); + using JsonDocument doc = JsonDocument.Parse(json); + JsonElement root = doc.RootElement; + if (root.TryGetProperty("etoro", out JsonElement etoro) && etoro.ValueKind == JsonValueKind.Object) + { + foreach (JsonProperty account in etoro.EnumerateObject()) + { + string api = Get(account.Value, "apiKey"); + string user = Get(account.Value, "userKey"); + if (api.Length > 0 && user.Length > 0) + { + p.Etoro[account.Name] = new EtoroKeys(api, user, Time(Get(account.Value, "savedUtc")) ?? DateTime.MinValue); + } + } + } + + if (root.TryGetProperty("telegram", out JsonElement telegram) && telegram.ValueKind == JsonValueKind.Object) + { + p.TelegramToken = Get(telegram, "botToken"); + p.TelegramSavedUtc = Time(Get(telegram, "savedUtc")); + } + + return p; + } + + private static string Get(JsonElement e, string name) => + e.ValueKind == JsonValueKind.Object && e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? string.Empty : string.Empty; + + private static DateTime? Time(string text) => + DateTime.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t) ? t : null; + } +} diff --git a/Encelado/src/Encelado.Engine/Engine/BotSnapshot.cs b/Encelado/src/Encelado.Engine/Engine/BotSnapshot.cs index 30ea9cb..8d75106 100644 --- a/Encelado/src/Encelado.Engine/Engine/BotSnapshot.cs +++ b/Encelado/src/Encelado.Engine/Engine/BotSnapshot.cs @@ -130,12 +130,30 @@ public sealed record BotSnapshot public TimeSpan Uptime { get; init; } - /// PAPER, DEMO, LIVE — the badge. + /// DEMO or LIVE — the badge. public required string Mode { get; init; } - /// paper, demo or live, for the badge colour. + /// demo or live, for the badge colour. public string EnvironmentKind { get; init; } = "demo"; + /// The eToro account the mode trades on: demo or live (the API's words). + public string Account { get; init; } = "demo"; + + /// The operator's pause (/pausa): no new entries, exits running. Survives a restart. + public bool Paused { get; init; } + + /// The secret store's state: open, empty, locked, localKey. + public string SecretsState { get; init; } = "empty"; + + /// The secrets are encrypted with another password: the engine cannot start until they are unlocked or reset. + public bool SecretsLocked => SecretsState == "locked"; + + /// Live mode and the engine stopped: it only starts with AVVIA and the phrase (it never starts by itself). + public bool LiveNeedsConfirmation { get; init; } + + /// Environment variables of 5.0 still set on the container and ignored since 5.1 ("puoi toglierle"). + public IReadOnlyList IgnoredEnv { get; init; } = []; + public string ExecutionMode { get; init; } = string.Empty; public string Endpoint { get; init; } = string.Empty; @@ -274,6 +292,18 @@ public sealed record PositionInfo(long PositionId, string Symbol, bool IsBuy, do public readonly record struct CommandResult(bool Ok, string Message) { + /// A command's answer that needs a person: the live phrase is missing. + public const string NeedsPhrase = "needsPhrase"; + + /// A settings change that only a fresh engine can take. + public const string RestartRequired = "restart"; + + /// Refused because of the state of the account (open baskets, pending orders). + public const string Refused = "refused"; + /// Structured data for the caller, when a message is not enough (the bonifica's list of positions). public object? Payload { get; init; } + + /// A machine-readable reason next to the message (, , ), or empty. + public string Code { get; init; } = string.Empty; } diff --git a/Encelado/src/Encelado.Engine/Engine/BotSupervisor.cs b/Encelado/src/Encelado.Engine/Engine/BotSupervisor.cs index 5fe7f6c..b0f7050 100644 --- a/Encelado/src/Encelado.Engine/Engine/BotSupervisor.cs +++ b/Encelado/src/Encelado.Engine/Engine/BotSupervisor.cs @@ -1,3 +1,4 @@ +using Encelado.Core.Baskets; using Encelado.Engine.Baskets; using Encelado.Engine.Configuration; using Encelado.Engine.Logging; @@ -5,49 +6,90 @@ using Encelado.Engine.Settings; namespace Encelado.Engine; +/// What the host knows that the engine does not: the secret store's state and the ignored variables. +public sealed record HostStatus(string SecretsState, IReadOnlyList IgnoredEnv) +{ + public static readonly HostStatus Unknown = new("empty", []); +} + /// -/// Owns the engine's lifecycle so the window can start and stop trading without +/// Owns the engine's lifecycle so the interface can start and stop trading without /// restarting the process, and assembles the snapshot the UI renders. /// /// Each start creates a fresh engine. Reusing one would mean resurrecting a /// connection, models and risk counters that were built to live exactly as long as a /// session does; a new instance is simpler and cannot leak stale state. /// +/// +/// The Live gate is an argument of every start (), never a flag +/// left behind by a previous one (5.1, decision C7): a start without the phrase typed by a +/// person — the autostart, an automatic restart — can never reach the real account. +/// /// public sealed class BotSupervisor(BotConfig config, Func? factory = null, Core.Notifications.INotifier? notifier = null) : IAsyncDisposable { - private readonly int _eventCapacity = Math.Max(20, config.Logging.StatusLines); private readonly Lock _gate = new(); private readonly Queue _events = new(); - private readonly Func _factory = factory ?? ((c, confirmed) => new BasketEngine(c, confirmed, null, notifier)); + private readonly Func _factory = factory ?? ((c, confirmed) => new BasketEngine(c, null, confirmed, null, notifier)); + private int _eventCapacity = Math.Max(20, config.Logging.StatusLines); private IEngine? _engine; private CancellationTokenSource? _engineCts; private Task? _engineTask; private BotState _state = BotState.Stopped; private string? _error; private DateTime? _startedUtc; + private bool _startedLive; public BotConfig Config => config; - /// Set by the shell once the operator has confirmed the live mode at start. - public bool StartConfirmed { get; set; } + /// The secret store's state and the ignored variables, merged into every snapshot (set by the host). + public Func? HostStatusProvider { get; set; } + + /// The cached strategy.json for the picture of a stopped engine (set by the host; parsed on each call otherwise). + public Func? StrategyProvider { get; set; } public BotState State { get { lock (_gate) { return _state; } } } - /// Mirrors the log into the activity feed shown in the window. + /// Running or starting: an engine exists and trades (or is about to). + public bool IsRunning => State is BotState.Running or BotState.Starting; + + /// Whether the engine that runs now was started in Live (the mode it was built with, not the file's). + public bool RunningLive + { + get { lock (_gate) { return _startedLive && _state is BotState.Running or BotState.Starting; } } + } + + /// Mirrors the log into the activity feed shown in the interface. public void AttachLogSink() => Log.Sink = RecordEvent; public void DetachLogSink() => Log.Sink = null; + /// How many lines the activity feed keeps (logging.statusLines, applied at once). + public void SetEventCapacity(int capacity) + { + lock (_gate) + { + _eventCapacity = Math.Max(20, capacity); + while (_events.Count > _eventCapacity) + { + _events.Dequeue(); + } + } + } + // ----------------------------------------------------------------------- // Lifecycle // ----------------------------------------------------------------------- - public async Task StartAsync() + /// + /// Builds and starts a fresh engine. is true only when + /// a person typed the phrase for this very start; the engine refuses Live without it. + /// + public async Task StartAsync(bool liveConfirmed = false) { lock (_gate) { @@ -70,7 +112,7 @@ public sealed class BotSupervisor(BotConfig config, Func StopAsync() + /// + /// Stops the engine. true (FERMA, the container's stop) + /// honours run.closeOnShutdown; false (the automatic restart after a settings + /// change) never closes anything: the next engine takes the baskets over from the state. + /// + public async Task StopAsync(bool closeBaskets = true) { CancellationTokenSource? cts; Task? task; @@ -163,7 +211,7 @@ public sealed class BotSupervisor(BotConfig config, FuncHands a saved change to the running engine (no-op when stopped: the next start reads the files). + public Task ApplySettingsAsync(IEnumerable paths, string reason, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(paths); + return IsRunning + ? ExecuteAsync(new EngineCommand(EngineCommandKind.ApplySettings, string.Join(',', paths), reason), ct) + : Task.FromResult(new CommandResult(true, "motore fermo: vale al prossimo avvio")); + } + /// Forwards a command to the running engine. public async Task ExecuteAsync(EngineCommand command, CancellationToken ct) { @@ -236,7 +294,7 @@ public sealed class BotSupervisor(BotConfig config, FuncCloses one basket on demand from the window or the console. + /// Closes one basket on demand from the interface or the console. public Task CloseAsync(string basket, CancellationToken ct) => ExecuteAsync(new EngineCommand(EngineCommandKind.Close, basket, "chiusura manuale"), ct); @@ -259,12 +317,18 @@ public sealed class BotSupervisor(BotConfig config, Func= _eventCapacity) + while (_events.Count >= _eventCapacity) { _events.Dequeue(); } diff --git a/Encelado/src/Encelado.Engine/Engine/IEngine.cs b/Encelado/src/Encelado.Engine/Engine/IEngine.cs index dbb4e11..8832c71 100644 --- a/Encelado/src/Encelado.Engine/Engine/IEngine.cs +++ b/Encelado/src/Encelado.Engine/Engine/IEngine.cs @@ -9,9 +9,6 @@ public enum EngineCommandKind /// Close everything now, block new entries until reset. Argument = esterne to close the foreign positions too. KillSwitch, - /// Change the style preset at runtime. Argument = Conservative | Moderate | Aggressive. - SetPreset, - /// /// The guided reset (§9 of the 5.0 plan): state, STOP file, written reason (at least /// ten characters, in Reason), reconciliation with warm-up and a fresh peak, @@ -38,6 +35,15 @@ public enum EngineCommandKind /// done switches the engine back to closing orphans on its own. /// Bonifica, + + /// + /// A save in Impostazioni (5.1, hot apply): the engine takes the new strategy.json + /// and the timeouts on its decision thread, recomputes the strategy's fingerprint and + /// writes a configurazione line in the ledger. Argument = the changed paths, + /// comma separated. Answers with restart when the + /// file changed what only a fresh engine can take (the pairs, the direct crosses). + /// + ApplySettings, } public sealed record EngineCommand(EngineCommandKind Kind, string Argument = "", string Reason = ""); diff --git a/Encelado/src/Encelado.Engine/Engine/SnapshotJson.cs b/Encelado/src/Encelado.Engine/Engine/SnapshotJson.cs index f25e269..a748003 100644 --- a/Encelado/src/Encelado.Engine/Engine/SnapshotJson.cs +++ b/Encelado/src/Encelado.Engine/Engine/SnapshotJson.cs @@ -37,6 +37,18 @@ public static class SnapshotJson w.WriteString("mode", s.Mode); w.WriteString("environmentKind", s.EnvironmentKind); w.WriteString("executionMode", s.ExecutionMode); + w.WriteString("account", s.Account); + w.WriteBoolean("paused", s.Paused); + w.WriteString("secretsState", s.SecretsState); + w.WriteBoolean("secretsLocked", s.SecretsLocked); + w.WriteBoolean("liveNeedsConfirmation", s.LiveNeedsConfirmation); + w.WriteStartArray("ignoredEnv"); + foreach (string v in s.IgnoredEnv) + { + w.WriteStringValue(v); + } + + w.WriteEndArray(); w.WriteString("endpoint", s.Endpoint); w.WriteString("preset", s.Preset); w.WriteString("strategyVersion", s.StrategyVersion); diff --git a/Encelado/src/Encelado.Engine/Logging/Log.cs b/Encelado/src/Encelado.Engine/Logging/Log.cs index 892f044..6e61cac 100644 --- a/Encelado/src/Encelado.Engine/Logging/Log.cs +++ b/Encelado/src/Encelado.Engine/Logging/Log.cs @@ -51,7 +51,7 @@ public static class Log private static Task? _writerTask; private static StreamWriter? _file; - private static LogLevel _minimum = LogLevel.Info; + private static volatile LogLevel _minimum = LogLevel.Info; private static bool _console = true; private static bool _colors; private static long _dropped; @@ -59,11 +59,17 @@ public static class Log private static long _processed; private static string? _path; private static long _maxBytes; - private static int _maxFiles = 10; + private static volatile int _maxFiles = 10; private static long _written; public static LogLevel Minimum => _minimum; + /// Lines accepted since the start (the diagnostics page shows them next to the dropped ones). + public static long Enqueued => Interlocked.Read(ref _enqueued); + + /// Lines lost because the queue or the writer failed. + public static long Dropped => Interlocked.Read(ref _dropped); + public static bool IsEnabled(LogLevel level) => level >= _minimum; /// @@ -80,7 +86,7 @@ public static class Log _minimum = ParseLevel(options.Level); _console = options.Console; _colors = _console && !Console.IsOutputRedirected; - _maxBytes = options.MaxFileSizeMb > 0 ? options.MaxFileSizeMb * 1024L * 1024L : 0; + Interlocked.Exchange(ref _maxBytes, options.MaxFileSizeMb > 0 ? options.MaxFileSizeMb * 1024L * 1024L : 0); _maxFiles = options.MaxFiles; _path = options.ResolvePath(options.File); @@ -88,6 +94,25 @@ public static class Log _writerTask ??= Task.Run(WriteLoopAsync); } + /// + /// Applies a saved change of the log settings at once (5.1): the level, the rotation size + /// and the number of rotated files. The file itself (folder and name) is fixed for the + /// process: calling again would open a second stream on it. + /// + public static void Reconfigure(LoggingOptions options) + { + ArgumentNullException.ThrowIfNull(options); + _minimum = ParseLevel(options.Level); + Interlocked.Exchange(ref _maxBytes, options.MaxFileSizeMb > 0 ? options.MaxFileSizeMb * 1024L * 1024L : 0); + _maxFiles = Math.Max(1, options.MaxFiles); + } + + /// The rotation size in bytes now in force (0 = no rotation). + public static long MaxBytes => Interlocked.Read(ref _maxBytes); + + /// The rotated files kept now. + public static int MaxFiles => _maxFiles; + /// Absolute path of the active log file, for the UI to show and open. public static string? FilePath => _path; @@ -150,7 +175,8 @@ public static class Log /// private static void RotateIfNeeded() { - if (_file is null || _maxBytes <= 0 || _written < _maxBytes || string.IsNullOrWhiteSpace(_path)) + long maxBytes = Interlocked.Read(ref _maxBytes); + if (_file is null || maxBytes <= 0 || _written < maxBytes || string.IsNullOrWhiteSpace(_path)) { return; } @@ -167,13 +193,14 @@ public static class Log string Slot(int i) => Path.Combine(directory, $"{name}.{i}{extension}"); - string oldest = Slot(_maxFiles); + int maxFiles = _maxFiles; + string oldest = Slot(maxFiles); if (File.Exists(oldest)) { File.Delete(oldest); } - for (int i = _maxFiles - 1; i >= 1; i--) + for (int i = maxFiles - 1; i >= 1; i--) { if (File.Exists(Slot(i))) { diff --git a/Encelado/src/Encelado.Engine/Settings/AccountActivity.cs b/Encelado/src/Encelado.Engine/Settings/AccountActivity.cs new file mode 100644 index 0000000..40c6043 --- /dev/null +++ b/Encelado/src/Encelado.Engine/Settings/AccountActivity.cs @@ -0,0 +1,85 @@ +using System.Globalization; +using System.Text.Json; +using Encelado.Core.Baskets; + +namespace Encelado.Engine.Settings; + +/// +/// What the bot holds on the account right now: open baskets, entries waiting for a leg, +/// orders without an outcome. A change of account (Demo ↔ Live) or of the basket pairs is +/// refused while any of these exists (5.1, decision C8): the other account does not have +/// them, and a basket left behind would be watched by nobody but the native stop-loss. +/// +public sealed record AccountActivity(int OpenBaskets, int PendingBaskets, int PendingOrders) +{ + public static readonly AccountActivity None = new(0, 0, 0); + + public bool Busy => OpenBaskets + PendingBaskets + PendingOrders > 0; + + public string Describe() => string.Create(CultureInfo.InvariantCulture, + $"{OpenBaskets} basket aperti, {PendingBaskets} in attesa di una gamba, {PendingOrders} ordini senza esito"); + + /// From the running engine's picture. + public static AccountActivity FromSnapshot(BotSnapshot snapshot) + { + ArgumentNullException.ThrowIfNull(snapshot); + return new AccountActivity(snapshot.OpenBaskets, snapshot.PendingBaskets, snapshot.PendingOrders); + } + + /// + /// From the files a stopped engine left: data/state/baskets_state.json (open and + /// pending baskets) and data/state/pending_orders.json (orders without an outcome). + /// An unreadable state counts as busy: refusing a switch is the prudent answer. + /// + public static AccountActivity FromDisk(string dataPath) + { + ArgumentException.ThrowIfNullOrWhiteSpace(dataPath); + string state = Path.Combine(dataPath, "state", "baskets_state.json"); + int open = 0, pending = 0; + if (File.Exists(state)) + { + try + { + using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(state)); + open = Count(doc.RootElement, "baskets"); + pending = Count(doc.RootElement, "pendingEntries"); + } + catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException) + { + open = 1; + } + } + + // Read here, not through OrderTracker: its loader moves an unreadable register aside, + // and a check made by the settings page must not touch the engine's files. + int orders = 0; + string register = Path.Combine(dataPath, "state", "pending_orders.json"); + if (File.Exists(register)) + { + try + { + using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(register)); + if (doc.RootElement.TryGetProperty("orders", out JsonElement all) && all.ValueKind == JsonValueKind.Array) + { + foreach (JsonElement o in all.EnumerateArray()) + { + string resolution = o.TryGetProperty("resolution", out JsonElement r) && r.ValueKind == JsonValueKind.String ? r.GetString() ?? string.Empty : string.Empty; + if (!Enum.TryParse(resolution, out OrderResolution parsed) || parsed == OrderResolution.Pending) + { + orders++; + } + } + } + } + catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException) + { + orders = 1; + } + } + + return new AccountActivity(open, pending, orders); + + static int Count(JsonElement root, string name) => + root.TryGetProperty(name, out JsonElement a) && a.ValueKind == JsonValueKind.Array ? a.GetArrayLength() : 0; + } +} diff --git a/Encelado/src/Encelado.Engine/Settings/AutostartPolicy.cs b/Encelado/src/Encelado.Engine/Settings/AutostartPolicy.cs new file mode 100644 index 0000000..88335dd --- /dev/null +++ b/Encelado/src/Encelado.Engine/Settings/AutostartPolicy.cs @@ -0,0 +1,52 @@ +using Encelado.Core.Baskets; +using Encelado.Engine.Configuration; + +namespace Encelado.Engine.Settings; + +/// What the process does with the engine when it starts. +public enum AutostartDecision +{ + /// Start the engine (Demo, autostart on). + Start = 0, + + /// run.autostart is off: the engine waits for AVVIA. + Disabled, + + /// The command line said --no-autostart (development). + NoAutostartFlag, + + /// --sample: no engine at all. + Sample, + + /// Live: never started without a person typing the phrase; the engine waits, an alarm and a Telegram alert say so. + LiveWaits, +} + +/// +/// Whether the engine starts with the process (5.1, decisions C7 and C9): run.autostart +/// (on by default) replaces the variable ENCELADO_AUTOSTART, the command line's +/// --no-autostart still wins for development, and Live never starts by itself. +/// +public static class AutostartPolicy +{ + public static AutostartDecision Decide(bool noAutostartFlag, bool sample, BotConfig config) + { + ArgumentNullException.ThrowIfNull(config); + if (sample) + { + return AutostartDecision.Sample; + } + + if (noAutostartFlag) + { + return AutostartDecision.NoAutostartFlag; + } + + if (!config.Run.Autostart) + { + return AutostartDecision.Disabled; + } + + return config.Run.Mode.IsLive() ? AutostartDecision.LiveWaits : AutostartDecision.Start; + } +} diff --git a/Encelado/src/Encelado.Engine/Settings/SettingField.cs b/Encelado/src/Encelado.Engine/Settings/SettingField.cs index baa9066..b2e4b80 100644 --- a/Encelado/src/Encelado.Engine/Settings/SettingField.cs +++ b/Encelado/src/Encelado.Engine/Settings/SettingField.cs @@ -4,17 +4,40 @@ using System.Text.Json.Nodes; namespace Encelado.Engine.Settings; -/// What a field accepts, which decides how it is parsed and validated. +/// What a field accepts, which decides how it is parsed and validated (the API's kind). public enum SettingKind { Text = 0, Integer, Number, - - /// Shown as a percentage, stored as a fraction. 20 on screen is 0.2 in the file. - Percent, Boolean, Choice, + + /// A list of short texts, comma separated on screen, a JSON array in the file (the entry sessions). + List, +} + +/// When a saved value takes effect (the API's scope). +public enum SettingScope +{ + /// At once, in the process: log, interface, notifications, the flags read at use. + Immediate = 0, + + /// At once in the running engine, on its decision thread (strategy, intervals, timeouts). + Engine, + + /// Only a fresh engine can take it: the running one is restarted (never closing a basket), Live asks for the phrase first. + Restart, +} + +/// Which file a field lives in. +public enum SettingTarget +{ + /// encelado.json. + Config = 0, + + /// strategy.json; the API path carries the prefix strategy:. + Strategy, } /// @@ -25,20 +48,29 @@ public enum SettingKind /// same place as everything else — hiding it in a paragraph makes the page read like /// documentation, and documentation is what people stop reading. /// +/// +/// Every value travels as a string (the API's rule): booleans as true/false, +/// numbers in invariant notation, lists comma separated. Input is lenient — sì/no +/// and a decimal comma are accepted — and normalised before it is compared or written. +/// /// public sealed class SettingField { + /// The prefix of the paths that live in strategy.json. + public const string StrategyPrefix = "strategy:"; + private string _value = string.Empty; private string? _error; + /// The path the API and the page use: run.pollSeconds, or strategy:preset for the strategy file. public required string Path { get; init; } public required string Label { get; init; } /// - /// The value as loaded from the configuration. Setting it establishes both the - /// current text and the baseline that compares against, so a - /// freshly built field is never reported as edited. + /// The value as loaded from the file. Setting it establishes both the current text and + /// the baseline that compares against, so a freshly built field is + /// never reported as edited. /// public required string Initial { @@ -54,7 +86,14 @@ public sealed class SettingField public SettingKind Kind { get; init; } = SettingKind.Text; - /// Fixed by the strategy. Visible and copyable, but not editable. + public SettingScope Scope { get; init; } = SettingScope.Immediate; + + public SettingTarget Target => Path.StartsWith(StrategyPrefix, StringComparison.Ordinal) ? SettingTarget.Strategy : SettingTarget.Config; + + /// The dotted path inside its own file (the API path without strategy:). + public string FilePath => Target == SettingTarget.Strategy ? Path[StrategyPrefix.Length..] : Path; + + /// Visible and copyable, but not editable. public bool IsReadOnly { get; init; } /// Why it cannot be edited. Appended to the tooltip. @@ -62,46 +101,23 @@ public sealed class SettingField public IReadOnlyList Choices { get; init; } = []; - /// - /// I valori fra cui si può scegliere, o vuoto se il campo è a testo libero. - /// - /// I booleani entrano qui da sé: "sì" e "no" scritti a mano sono due modi per - /// sbagliare, e nessuno dei due aggiunge niente rispetto a sceglierli. - /// - /// - public IReadOnlyList Options => Kind switch - { - SettingKind.Choice => Choices, - SettingKind.Boolean => ["sì", "no"], - _ => [], - }; - - /// Vero se il campo si compila da un elenco. Vedi . - public bool IsList => Options.Count > 0; - - /// Vero se il campo si scrive. È l'opposto di . - public bool IsFreeText => !IsList; - - /// - /// Vero quando il valore salvato non è più fra quelli ammessi — tipicamente dopo un - /// aggiornamento che ha tolto una strategia. Il campo resta visibile con il suo - /// errore, ma l'elenco non lo ripropone: da lì si esce solo scegliendo un valore - /// che esiste. - /// - public bool IsObsolete => IsList && !IsReadOnly && - !Options.Contains(_value, StringComparer.OrdinalIgnoreCase); + /// The values a offers; empty for every other kind. + public IReadOnlyList Options => Kind == SettingKind.Choice ? Choices : []; /// Unit suffix shown after the box, e.g. "%" or "secondi". public string Suffix { get; init; } = string.Empty; - /// A text field that means "use the default" when left blank. + /// + /// May be left empty. For a text it means "none"; for a number it means "remove the key + /// from the file" — the preset overrides of the strategy, where empty is "the preset's value". + /// public bool AllowEmpty { get; init; } public double Minimum { get; init; } = double.NegativeInfinity; public double Maximum { get; init; } = double.PositiveInfinity; - /// The value as first loaded, so edits can be detected and reverted. + /// The value as first loaded, so edits can be detected. public string Original { get; private set; } = string.Empty; public string Value @@ -109,65 +125,64 @@ public sealed class SettingField get => _value; set { - if (_value == value) - { - return; - } - - _value = value; + _value = Normalise(value ?? string.Empty); Validate(); } } - public string? Error - { - get => _error; - private set - { - if (_error == value) - { - return; - } - - _error = value; - } - } + public string? Error => _error; public bool HasError => _error is not null; - public bool IsDirty => !IsReadOnly && _value != Original; + public bool IsDirty => !IsReadOnly && !string.Equals(Normalise(_value), Normalise(Original), StringComparison.Ordinal); + + /// An empty value that means "remove the key" (see ). + public bool IsDeletion => AllowEmpty && _value.Length == 0 && Kind is SettingKind.Integer or SettingKind.Number; public string FullTooltip => ReadOnlyReason is null ? Tooltip : $"{Tooltip}\n\nNON MODIFICABILE — {ReadOnlyReason}"; - public void Load(string value) + /// The kind as the API spells it. + public string KindName => Kind switch { - _value = value; - Original = value; + SettingKind.Integer => "integer", + SettingKind.Number => "number", + SettingKind.Boolean => "bool", + SettingKind.Choice => "choice", + SettingKind.List => "list", + _ => "text", + }; - // Validato subito, non solo quando qualcuno lo tocca: un valore diventato non - // valido perché l'aggiornamento ha tolto una strategia deve segnalarsi da sé - // all'apertura della pagina, non restare lì con l'aria di andare bene. - Validate(); - } + /// The scope as the API spells it. + public string ScopeName => Scope switch + { + SettingScope.Engine => "engine", + SettingScope.Restart => "restart", + _ => "immediate", + }; - /// Checks the text in isolation. Cross-field rules are the config's own job. + /// Checks the text in isolation. Cross-field rules are the file's own validator's job. public void Validate() { - Error = null; + _error = null; if (IsReadOnly) { return; } + if (_value.Length == 0 && AllowEmpty) + { + return; + } + switch (Kind) { case SettingKind.Integer: - if (!int.TryParse(_value, NumberStyles.Integer, CultureInfo.CurrentCulture, out int i)) + if (!TryNumber(_value, out double i) || i != Math.Round(i)) { - Error = "serve un numero intero"; + _error = "serve un numero intero"; } else { @@ -177,10 +192,9 @@ public sealed class SettingField break; case SettingKind.Number: - case SettingKind.Percent: - if (!double.TryParse(_value, NumberStyles.Float, CultureInfo.CurrentCulture, out double d)) + if (!TryNumber(_value, out double d)) { - Error = "serve un numero"; + _error = "serve un numero"; } else { @@ -190,9 +204,9 @@ public sealed class SettingField break; case SettingKind.Boolean: - if (!bool.TryParse(_value, out _) && _value is not ("sì" or "no" or "si")) + if (!TryBool(_value, out _)) { - Error = "serve sì o no"; + _error = "serve true o false"; } break; @@ -200,16 +214,28 @@ public sealed class SettingField case SettingKind.Choice: if (Choices.Count > 0 && !Choices.Contains(_value, StringComparer.OrdinalIgnoreCase)) { - Error = $"'{_value}' non è più disponibile — scegli fra: {string.Join(", ", Choices)}"; + _error = $"'{_value}' non è fra i valori ammessi: {string.Join(", ", Choices)}"; + } + + break; + + case SettingKind.List: + foreach (string item in Items(_value)) + { + if (!IsSession(item)) + { + _error = $"'{item}' non è una fascia oraria UTC nella forma HH-HH (es. 07-16)"; + break; + } } break; case SettingKind.Text: default: - if (_value.Length == 0 && !AllowEmpty) + if (_value.Length == 0) { - Error = "non può essere vuoto"; + _error = "non può essere vuoto"; } break; @@ -219,50 +245,104 @@ public sealed class SettingField { if (v < Minimum) { - Error = $"non può essere sotto {Minimum.ToString("0.####", CultureInfo.CurrentCulture)}"; + _error = $"non può essere sotto {Minimum.ToString("0.####", CultureInfo.InvariantCulture)}"; } else if (v > Maximum) { - Error = $"non può essere sopra {Maximum.ToString("0.####", CultureInfo.CurrentCulture)}"; + _error = $"non può essere sopra {Maximum.ToString("0.####", CultureInfo.InvariantCulture)}"; } } } - /// The value as it must be written to the JSON file. + /// The value as it must be written to the JSON file (never called for a deletion). public JsonNode? ToJson() => Kind switch { - SettingKind.Integer => JsonValue.Create(int.Parse(_value, CultureInfo.CurrentCulture)), - SettingKind.Number => JsonValue.Create(double.Parse(_value, NumberStyles.Float, CultureInfo.CurrentCulture)), - - // Shown as 20, stored as 0.2. Rounded because 20/100 in binary floating point is - // 0.200000000000000011, and writing that into a hand-edited file is unkind. - SettingKind.Percent => JsonValue.Create( - Math.Round(double.Parse(_value, NumberStyles.Float, CultureInfo.CurrentCulture) / 100.0, 10)), - - // "no" is a valid answer and bool.Parse throws on it, so the Italian words are - // resolved first and anything unrecognised falls through to false. - SettingKind.Boolean => JsonValue.Create( - _value is "sì" or "si" || (bool.TryParse(_value, out bool flag) && flag)), + SettingKind.Integer => JsonValue.Create((int)Math.Round(ParseNumber(_value))), + SettingKind.Number => JsonValue.Create(Math.Round(ParseNumber(_value), 10)), + SettingKind.Boolean => JsonValue.Create(TryBool(_value, out bool flag) && flag), + SettingKind.List => new JsonArray([.. Items(_value).Select(static s => (JsonNode?)JsonValue.Create(s))]), + SettingKind.Choice => JsonValue.Create(Choices.FirstOrDefault(c => c.Equals(_value, StringComparison.OrdinalIgnoreCase)) ?? _value), _ => JsonValue.Create(_value), }; - /// Formats a stored value for display, inverting . - public static string Format(double value, SettingKind kind) => kind switch + /// A number for display and for the API: invariant, no trailing zeros. + public static string Format(double value) => + double.IsFinite(value) ? value.ToString("0.##########", CultureInfo.InvariantCulture) : string.Empty; + + public static string Format(int value) => value.ToString(CultureInfo.InvariantCulture); + + public static string Format(bool value) => value ? "true" : "false"; + + /// Parses a number the way a person types it: invariant notation, or a single decimal comma. + public static bool TryNumber(string text, out double value) { - SettingKind.Percent => Math.Round(value * 100, 6).ToString("0.####", CultureInfo.CurrentCulture), - SettingKind.Integer => ((int)Math.Round(value)).ToString(CultureInfo.CurrentCulture), - _ => value.ToString("0.######", CultureInfo.CurrentCulture), - }; + string t = (text ?? string.Empty).Trim().Replace(" ", string.Empty, StringComparison.Ordinal); + if (t.Contains(',', StringComparison.Ordinal) && !t.Contains('.', StringComparison.Ordinal)) + { + t = t.Replace(',', '.'); + } + return double.TryParse(t, NumberStyles.Float, CultureInfo.InvariantCulture, out value) && double.IsFinite(value); + } + public static bool TryBool(string text, out bool value) + { + switch ((text ?? string.Empty).Trim().ToLowerInvariant()) + { + case "true" or "1" or "sì" or "si" or "yes" or "on": + value = true; + return true; + case "false" or "0" or "no" or "off": + value = false; + return true; + default: + value = false; + return false; + } + } + + private static double ParseNumber(string text) => TryNumber(text, out double v) ? v : throw new FormatException($"'{text}' non è un numero"); + + private string Normalise(string text) + { + string t = text.Trim(); + return Kind switch + { + SettingKind.Boolean when TryBool(t, out bool b) => Format(b), + SettingKind.Integer or SettingKind.Number when t.Length > 0 && TryNumber(t, out double d) => Format(d), + SettingKind.List => string.Join(",", Items(t)), + SettingKind.Choice => Choices.FirstOrDefault(c => c.Equals(t, StringComparison.OrdinalIgnoreCase)) ?? t, + _ => t, + }; + } + + private static IEnumerable Items(string text) => + text.Split([',', ';', ' '], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + + private static bool IsSession(string item) + { + string[] parts = item.Split('-'); + return parts.Length == 2 && + int.TryParse(parts[0], NumberStyles.None, CultureInfo.InvariantCulture, out int from) && + int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out int to) && + from is >= 0 and <= 23 && to is >= 0 and <= 24 && from != to; + } } /// A titled block of fields on the settings page. -public sealed class SettingGroup(string title, string description) +public sealed class SettingGroup(string key, string title, string description, SettingTarget target, bool advanced = false) { + /// A stable identifier for the page (conto, strategia…). + public string Key { get; } = key; + public string Title { get; } = title; public string Description { get; } = description; - public ObservableCollection Fields { get; } = []; + public SettingTarget Target { get; } = target; + + /// Shown collapsed: the preset overrides, the indicators, the windows and the thresholds. + public bool Advanced { get; } = advanced; + + public Collection Fields { get; } = []; } diff --git a/Encelado/src/Encelado.Engine/Settings/SettingsCatalogue.cs b/Encelado/src/Encelado.Engine/Settings/SettingsCatalogue.cs index ade0cc6..13f1200 100644 --- a/Encelado/src/Encelado.Engine/Settings/SettingsCatalogue.cs +++ b/Encelado/src/Encelado.Engine/Settings/SettingsCatalogue.cs @@ -1,28 +1,37 @@ -using System.Globalization; +using Encelado.Core.Baskets; using Encelado.Engine.Configuration; namespace Encelado.Engine.Settings; /// -/// The settings form, as data: which fields exist, where each one lives in the JSON, -/// what it means and what values it may take. The page renders this; it never knows a -/// path by name. Every tooltip says why the value is what it is, not only what it is. -/// The strategy's own numbers live in strategy.json, which the page opens as a -/// file: every value there is documented in place and a change is a decision the forward -/// test judges. +/// The settings form, as data (5.1, decision C12): which fields exist, which file each one +/// lives in, where in the JSON, what it means, what values it may take and when a change +/// takes effect. The page renders this; it never knows a path by name. Every tooltip says +/// why the value is what it is, not only what it is, and none mentions an environment +/// variable: since 5.1 everything is set here. +/// +/// Groups: Conto, Esecuzione, Strategia, Avanzate (collapsed: preset overrides, +/// indicators, windows, thresholds), Notifiche Telegram, Interfaccia, Log. The secrets (the +/// eToro keys of both accounts, the Telegram token) are not fields: the page shows them +/// from the secrets part of the answer and saves them through their own routes. +/// Paths, the endpoint, the user agent and the log folder are not exposed. +/// /// public static class SettingsCatalogue { - public static IReadOnlyList Build(BotConfig config) + public static IReadOnlyList Build(BotConfig config, BasketStrategyConfig strategy) { ArgumentNullException.ThrowIfNull(config); + ArgumentNullException.ThrowIfNull(strategy); List groups = [ + Account(config), Execution(config), - Etoro(config), - Window(config), - Notifications(config), + Strategy(strategy), + Advanced(strategy), + Telegram(config), + Interface(config), Logging(config), ]; @@ -36,62 +45,107 @@ public static class SettingsCatalogue return groups; } - private static SettingGroup Execution(BotConfig config) + /// Every field of the catalogue by path (case-insensitive). + public static Dictionary Index(IEnumerable groups) => + groups.SelectMany(static g => g.Fields).ToDictionary(static f => f.Path, StringComparer.OrdinalIgnoreCase); + + private static string B(bool v) => SettingField.Format(v); + + private static string N(double v) => SettingField.Format(v); + + private static string I(int v) => SettingField.Format(v); + + private const string S = SettingField.StrategyPrefix; + + // ----------------------------------------------------------------------- + // Conto + // ----------------------------------------------------------------------- + + private static SettingGroup Account(BotConfig config) { - SettingGroup g = new( - "Esecuzione", - "Dove vanno gli ordini. In ogni modalità il bot apre e chiude i basket da solo, senza chiedere conferma " + - "per il singolo ordine. I parametri della strategia (preset, soglie, rischio) stanno in strategy.json."); + SettingGroup g = new("conto", "Conto", + "Su quale conto eToro lavora il bot. Demo è il conto demo (ordini veri, denaro virtuale); Live il conto reale. " + + "Le chiavi dei due conti si inseriscono qui sotto e restano cifrate con la password dell'interfaccia.", + SettingTarget.Config); g.Fields.Add(new SettingField { Path = "run.executionMode", - Label = "Modalità", - Initial = config.Run.Mode.ToString(), + Label = "Conto", + Initial = config.Run.Mode.IsLive() ? "Live" : "Demo", Kind = SettingKind.Choice, - Choices = ["Paper", "Demo", "Live"], - Tooltip = "Paper: simulatore locale sopra le quotazioni reali, nessun ordine sul conto. Demo: conto demo di eToro, " + - "ordini veri e denaro virtuale. Live: conto reale, richiede il flag qui sotto e la frase CONFERMO LIVE a ogni avvio.", + Choices = ["Demo", "Live"], + Scope = SettingScope.Restart, + Tooltip = "Demo: il conto demo di eToro, ordini veri e denaro virtuale. Live: il conto reale; serve «Consenti il conto reale» " + + "e la frase CONFERMO LIVE a ogni avvio, e il motore non parte mai da solo. Il cambio è rifiutato finché ci sono basket " + + "aperti o ordini in sospeso (chiudili, anche con il kill-switch) e richiede le chiavi del conto scelto. Con il motore acceso " + + "lo riavvia da sé, senza chiudere niente.", }); g.Fields.Add(new SettingField { Path = "run.allowLive", Label = "Consenti il conto reale", - Initial = config.Run.AllowLive ? "sì" : "no", + Initial = B(config.Run.AllowLive), Kind = SettingKind.Boolean, - Tooltip = "Senza questo flag la modalità Live viene rifiutata all'avvio. Anche con il flag, l'avvio chiede di scrivere CONFERMO LIVE.", + Tooltip = "Senza questo interruttore la modalità Live viene rifiutata. Anche con l'interruttore acceso, ogni avvio in Live chiede di scrivere CONFERMO LIVE.", + }); + + return g; + } + + // ----------------------------------------------------------------------- + // Esecuzione + // ----------------------------------------------------------------------- + + private static SettingGroup Execution(BotConfig config) + { + SettingGroup g = new("esecuzione", "Esecuzione", + "Come gira il motore. In ogni modalità il bot apre e chiude i basket da solo, senza chiedere conferma per il singolo ordine.", + SettingTarget.Config); + + g.Fields.Add(new SettingField + { + Path = "run.autostart", + Label = "Avvio automatico", + Initial = B(config.Run.Autostart), + Kind = SettingKind.Boolean, + Tooltip = "Acceso: all'avvio del container il motore parte da solo. Mai in Live, che aspetta AVVIA con la frase CONFERMO LIVE " + + "(e manda un avviso). Vale dal prossimo avvio del container.", }); g.Fields.Add(new SettingField { Path = "run.closeOnShutdown", Label = "Chiudi i basket all'arresto", - Initial = config.Run.CloseOnShutdown ? "sì" : "no", + Initial = B(config.Run.CloseOnShutdown), Kind = SettingKind.Boolean, - Tooltip = "Con 'sì' fermare il bot chiude i basket aperti a mercato. Con 'no' restano sul conto con gli stop nativi sul " + - "server, ma senza nessuno che applichi il take-profit o lo stop di basket finché il bot non riparte.", + Tooltip = "Acceso: FERMA e lo spegnimento del container chiudono i basket aperti a mercato. Spento: restano sul conto con gli stop " + + "nativi sul server, ma senza nessuno che applichi il take-profit o lo stop di basket finché il bot non riparte. " + + "Un riavvio automatico dopo un cambio delle impostazioni non chiude mai niente.", }); g.Fields.Add(new SettingField { Path = "run.pollSeconds", Label = "Lettura quotazioni ogni", - Initial = config.Run.PollSeconds.ToString(CultureInfo.CurrentCulture), + Initial = I(config.Run.PollSeconds), Kind = SettingKind.Integer, + Scope = SettingScope.Engine, Suffix = "secondi", Minimum = 2, Maximum = 30, Tooltip = "Una richiesta per tutti gli strumenti. 3 s = 20 richieste al minuto su una quota condivisa di 120: " + - "resta spazio per candele e costi. TP e stop di basket vengono controllati a ogni lettura.", + "resta spazio per candele e costi. Take-profit e stop di basket vengono controllati a ogni lettura.", }); g.Fields.Add(new SettingField { Path = "run.statusSeconds", Label = "Riga di stato ogni", - Initial = config.Run.StatusSeconds.ToString(CultureInfo.CurrentCulture), + Initial = I(config.Run.StatusSeconds), Kind = SettingKind.Integer, + Scope = SettingScope.Engine, Suffix = "secondi", Minimum = 10, Maximum = 3600, @@ -100,145 +154,299 @@ public static class SettingsCatalogue g.Fields.Add(new SettingField { - Path = "run.paperStartingBalance", - Label = "Saldo iniziale paper", - Initial = SettingField.Format(config.Run.PaperStartingBalance, SettingKind.Number), - Kind = SettingKind.Number, - Suffix = "USD", + Path = "etoro.fillTimeoutSeconds", + Label = "Attesa esito ordine", + Initial = I(config.Etoro.FillTimeoutSeconds), + Kind = SettingKind.Integer, + Scope = SettingScope.Engine, + Suffix = "secondi", Minimum = 1, - Tooltip = "Il conto virtuale del simulatore locale (solo in modalità Paper).", - }); - - g.Fields.Add(new SettingField - { - Path = "run.paperSlippagePips", - Label = "Slippage paper", - Initial = SettingField.Format(config.Run.PaperSlippagePips, SettingKind.Number), - Kind = SettingKind.Number, - Suffix = "pip per gamba", - Minimum = 0, - Maximum = 10, - Tooltip = "Quanto il simulatore peggiora ogni esecuzione oltre lo spread reale del momento.", - }); - - return g; - } - - private static SettingGroup Etoro(BotConfig config) - { - SettingGroup g = new( - "eToro", - "Il collegamento a eToro Public API. Le chiavi non sono qui: si inseriscono dalla finestra di accesso e vivono " + - "cifrate nei dati dell'utente, una coppia per ambiente."); - - g.Fields.Add(new SettingField - { - Path = "etoro.environment", - Label = "Ambiente", - Initial = config.Etoro.IsDemo ? "demo" : "real", - Kind = SettingKind.Choice, - Choices = ["demo", "real"], - Tooltip = "demo: il conto virtuale di eToro, ordini veri e soldi finti. real: il conto reale, che richiede " + - "la modalità Live, run.allowLive e la frase CONFERMO LIVE a ogni avvio. Cambiare ambiente richiede le chiavi di quell'ambiente.", + Maximum = 60, + Tooltip = "eToro lavora gli ordini in modo asincrono: il bot interroga l'esito per questo tempo, poi tratta l'ordine come " + + "non confermato, lo lascia nel registro e riconcilia con le posizioni sul conto. È anche il timeout della seconda gamba (leg-risk).", }); g.Fields.Add(new SettingField { Path = "etoro.requestTimeoutSeconds", Label = "Timeout richieste", - Initial = config.Etoro.RequestTimeoutSeconds.ToString(CultureInfo.CurrentCulture), + Initial = I(config.Etoro.RequestTimeoutSeconds), Kind = SettingKind.Integer, + Scope = SettingScope.Engine, Suffix = "secondi", Minimum = 3, Maximum = 120, - Tooltip = "Oltre questo tempo una richiesta HTTP viene abbandonata (e, se era una lettura, ritentata).", - }); - - g.Fields.Add(new SettingField - { - Path = "etoro.fillTimeoutSeconds", - Label = "Attesa esito ordine", - Initial = config.Etoro.FillTimeoutSeconds.ToString(CultureInfo.CurrentCulture), - Kind = SettingKind.Integer, - Suffix = "secondi", - Minimum = 1, - Maximum = 60, - Tooltip = "eToro lavora gli ordini in modo asincrono: il bot interroga l'esito per questo tempo, poi tratta " + - "l'ordine come non confermato e riconcilia con le posizioni sul conto. È anche il timeout della seconda gamba (leg-risk).", + Tooltip = "Oltre questo tempo una richiesta HTTP a eToro viene abbandonata (e, se era una lettura, ritentata).", }); return g; } - private static SettingGroup Window(BotConfig config) + // ----------------------------------------------------------------------- + // Strategia + // ----------------------------------------------------------------------- + + private static SettingGroup Strategy(BasketStrategyConfig s) { - SettingGroup g = new( - "Interfaccia", - "Come l'interfaccia mostra le cose. Niente qui cambia quello che il bot fa."); + SettingGroup g = new("strategia", "Strategia", + "Il preset, i basket, il rischio e i cancelli d'ingresso (strategy.json). Un cambio vale subito per i basket nuovi: " + + "quelli aperti tengono take-profit, perdita massima, zStop e aggiunte con cui sono entrati. Ogni cambio finisce nel ledger " + + "con l'impronta della strategia.", + SettingTarget.Strategy); + BasketPreset c = BasketPresets.Conservative, m = BasketPresets.Moderate, a = BasketPresets.Aggressive; g.Fields.Add(new SettingField { - Path = "ui.timeZone", - Label = "Fuso orario", - Initial = config.Ui.TimeZone, + Path = S + "preset", + Label = "Preset", + Initial = s.Preset.ToString(), Kind = SettingKind.Choice, - Choices = UiClock.Choices(), - Tooltip = "Il fuso con cui l'interfaccia mostra ogni orario (orologio in alto, eventi, righe di attività). " + - "'computer' usa quello del sistema (TZ nel container). Il file di log porta l'offset e il ledger è in UTC: " + - "cambiare questo valore non tocca nessun file. Ha effetto al prossimo avvio.", + Choices = ["Conservative", "Moderate", "Aggressive"], + Scope = SettingScope.Engine, + Tooltip = FormattableString.Invariant( + $"Fissa sei numeri. Conservative: zIn {c.ZIn}, rischio {c.RiskPerBasketPct} % per basket, {c.MaxBaskets} basket, TP {c.TpPips} pip, {c.MaxAdds} aggiunte, zStop {c.ZStop}. ") + + FormattableString.Invariant( + $"Moderate: zIn {m.ZIn}, rischio {m.RiskPerBasketPct} %, {m.MaxBaskets} basket, TP {m.TpPips} pip, {m.MaxAdds} aggiunta, zStop {m.ZStop}. ") + + FormattableString.Invariant( + $"Aggressive: zIn {a.ZIn}, rischio {a.RiskPerBasketPct} %, {a.MaxBaskets} basket, TP {a.TpPips} pip, {a.MaxAdds} aggiunte, zStop {a.ZStop}. ") + + "I valori in Avanzate ▸ Sovrascritture, se compilati, prevalgono. Il bandit propone un preset ma non lo cambia mai: lo sceglie solo chi opera.", }); - g.Fields.Add(new SettingField + for (int i = 0; i < s.Baskets.Count; i++) { - Path = "ui.displayCurrency", - Label = "Valuta di visualizzazione", - Initial = config.Ui.DisplayCurrency, - Kind = SettingKind.Choice, - Choices = UiOptions.Currencies, - Tooltip = "La valuta in cui l'interfaccia, Telegram e le esportazioni mostrano gli importi. I tassi vengono dalle quotazioni eToro " + - "già in polling (EURUSD, GBPUSD, USDCHF, USDJPY, AUDUSD, USDCAD, NZDUSD); ogni importo convertito porta nel tooltip il valore in USD " + - "e il tasso usato. Ledger, baskets.csv e ogni decisione restano in USD. Cambia subito, senza riavvio.", - }); + BasketDefinition d = s.Baskets[i]; + string cross = SyntheticCross.TryDerive(d.A, d.B, out SyntheticCross? x) && x is not null ? x.Symbol : "?"; + g.Fields.Add(new SettingField + { + Path = FormattableString.Invariant($"{S}baskets[{i}].enabled"), + Label = $"Basket {d.A}/{d.B} ({cross})", + Initial = B(d.Enabled), + Kind = SettingKind.Boolean, + Scope = SettingScope.Engine, + Tooltip = $"Acceso: il bot può aprire questo basket. Spento: niente nuove entrate né aggiunte; un basket già aperto continua a essere " + + $"seguito fino alla chiusura (take-profit, stop, time-stop). {d.Note}".TrimEnd(), + }); + } - g.Fields.Add(new SettingField - { - Path = "ui.theme", - Label = "Tema", - Initial = config.Ui.Theme, - Kind = SettingKind.Choice, - Choices = ["dark", "light"], - Tooltip = "Palette scura (predefinita) o chiara, secondo i ruoli di colore di Material Design 3.", - }); + // Risk and safety. + g.Fields.Add(Number(S + "equityStopPct", "Equity stop", s.EquityStopPct, "% dal picco", 0.1, 50, SettingScope.Engine, + "Perdita dal picco di equity (al netto dei movimenti di cassa) oltre la quale il bot chiude tutto e si blocca fino al reset manuale con motivazione.")); + g.Fields.Add(Number(S + "dailyLossPct", "Perdita giornaliera massima", s.DailyLossPct, "% dell'equity", 0.1, 50, SettingScope.Engine, + "Calo dell'equity netta dalla mezzanotte UTC (cassa esclusa) oltre il quale niente nuove entrate fino al giorno dopo; le uscite restano attive.")); + g.Fields.Add(Number(S + "maxLossPerBasketPct", "Perdita massima per basket", s.MaxLossPerBasketPct, "% dell'equity", 0.1, 20, SettingScope.Engine, + "Stop di basket sul P&L netto, fissato all'ingresso in USD: un basket già aperto tiene il limite con cui è entrato.")); + g.Fields.Add(Number(S + "risk.maxMarginUsePct", "Margine totale massimo", s.Risk.MaxMarginUsePct, "% dell'equity", 1, 100, SettingScope.Engine, + "Margine impegnato da tutte le posizioni dopo l'apertura di un basket. La size è il minimo fra quella a rischio e quella a margine.")); + g.Fields.Add(Number(S + "risk.maxMarginPerBasketPct", "Margine massimo per basket", s.Risk.MaxMarginPerBasketPct, "% dell'equity", 1, 100, SettingScope.Engine, + "Margine delle due gambe di un basket. Non può superare il margine totale massimo.")); + g.Fields.Add(Number(S + "risk.marginBufferPct", "Margine di sicurezza sul disponibile", s.Risk.MarginBufferPct, "%", 0, 200, SettingScope.Engine, + "Il disponibile deve superare il margine richiesto di questa percentuale prima di inviare la gamba A e, ricontrollato, prima della B (altrimenti A viene richiusa).")); + g.Fields.Add(Number(S + "risk.marginCallBlockRatio", "Blocco entrate sotto equity/margine", s.Risk.MarginCallBlockRatio, "×", 1, 10, SettingScope.Engine, + "Sotto questo rapporto fra equity e margine usato niente nuove entrate.")); + g.Fields.Add(Number(S + "risk.marginCallCloseRatio", "Chiusura sotto equity/margine", s.Risk.MarginCallCloseRatio, "×", 1, 10, SettingScope.Engine, + "Sotto questo rapporto il bot chiude il basket con il P&L peggiore, per allontanare la margin call.")); + g.Fields.Add(Bool(S + "risk.closeForeignOnKill", "Il kill-switch chiude anche le posizioni esterne", s.Risk.CloseForeignOnKill, SettingScope.Engine, + "Acceso: il kill-switch chiude anche le posizioni che il bot non ha aperto. Spento (di fabbrica): le lascia stare, come sempre.")); + // Recovery. + g.Fields.Add(Integer(S + "recovery.thresholdMinutes", "Recupero dopo un'assenza di", s.Recovery.ThresholdMinutes, "minuti", 1, 1440, SettingScope.Engine, + "Più di così senza heartbeat o senza un ciclo (riavvio, sospensione, container fermo): prima di ogni entrata il bot risolve gli ordini, riconcilia, " + + "riscalda le serie e rivaluta ogni basket aperto.")); + g.Fields.Add(Integer(S + "recovery.warmupMinutes", "Riscaldamento dopo recupero o reset", s.Recovery.WarmupMinutes, "minuti", 0, 1440, SettingScope.Engine, + "Per quanto le entrate restano bloccate dopo un recupero o un reset, mentre le quotazioni si assestano.")); + g.Fields.Add(Integer(S + "recovery.heartbeatSeconds", "Heartbeat ogni", s.Recovery.HeartbeatSeconds, "secondi", 5, 600, SettingScope.Engine, + "Ogni quanto il bot scrive data/state/heartbeat.json: è la prova, per il recupero e per il controllo di salute del container, che il ciclo gira.")); + + // Learning (ADR-0006). + g.Fields.Add(Bool(S + "learning.enabled", "Apprendimento attivo", s.Learning.Enabled, SettingScope.Engine, + "Spento di fabbrica (ADR-0006): la logistica resta in ombra e p_ML è solo una colonna del ledger. Acceso: il cancello ML può attivarsi e " + + "il ciclo settimanale e il challenger possono girare. Accendilo solo dopo il criterio di riattivazione (300 basket chiusi in Demo, P&L forward ≥ 0).")); + g.Fields.Add(Bool(S + "learning.weeklyCycle", "Ciclo settimanale nel bot", s.Learning.WeeklyCycle, SettingScope.Engine, + "Con l'apprendimento attivo, il ciclo di addestramento gira nel bot la domenica dopo le 10 UTC.")); + g.Fields.Add(Bool(S + "learning.challenger", "Challenger MLP", s.Learning.Challenger, SettingScope.Engine, + "Con l'apprendimento attivo, il ciclo addestra anche la piccola rete neurale che sfida la logistica.")); + + // Cost gate. + g.Fields.Add(Number(S + "costMultiple", "Il TP deve valere almeno", s.CostMultiple, "× il costo", 1, 20, SettingScope.Engine, + "Entrata solo se il take-profit vale almeno questo multiplo del costo del giro (spread reali delle due gambe, markup dell'API, overnight stimato).")); + g.Fields.Add(Number(S + "spreadMedianMultiple", "Spread massimo all'ingresso", s.SpreadMedianMultiple, "× la mediana 24 h", 1, 20, SettingScope.Engine, + "Entrata solo se lo spread di ogni gamba non supera questo multiplo della sua mediana delle ultime 24 ore.")); + g.Fields.Add(Number(S + "spreadAnomalyMultiple", "Spread anomalo (chiusura forzata)", s.SpreadAnomalyMultiple, "× la mediana 24 h", 1, 50, SettingScope.Engine, + "Uno spread oltre questo multiplo per tre chiusure di barra di fila chiude il basket aperto.")); + g.Fields.Add(Number(S + "overnightPipsPerDay", "Overnight stimato", s.OvernightPipsPerDay, "pip al giorno", 0, 50, SettingScope.Engine, + "Usato dal cancello dei costi quando l'API non dà il costo overnight dello strumento.")); + + // Calendar and time. + g.Fields.Add(Integer(S + "blackoutBeforeMin", "Niente entrate prima di un evento", s.BlackoutBeforeMin, "minuti", 0, 720, SettingScope.Engine, + "Minuti prima di un evento ad alto impatto sulle valute del basket in cui non si entra.")); + g.Fields.Add(Integer(S + "blackoutAfterMin", "Niente entrate dopo un evento", s.BlackoutAfterMin, "minuti", 0, 720, SettingScope.Engine, + "Minuti dopo un evento ad alto impatto in cui non si entra.")); + g.Fields.Add(Integer(S + "fridayCutoffUtcHour", "Stop entrate del venerdì", s.FridayCutoffUtcHour, "ora UTC", 0, 23, SettingScope.Engine, + "Dal venerdì a quest'ora UTC fino alla riapertura niente nuove entrate: nessun basket nuovo attraversa il fine settimana.")); + g.Fields.Add(Integer(S + "openDelayMinutes", "Attesa dopo l'apertura settimanale", s.OpenDelayMinutes, "minuti", 0, 720, SettingScope.Engine, + "Minuti dopo la riapertura della domenica sera in cui non si entra: spread larghi e prezzi instabili.")); g.Fields.Add(new SettingField { - Path = "ui.navExpanded", - Label = "Barra di navigazione aperta", - Initial = config.Ui.NavExpanded ? "sì" : "no", - Kind = SettingKind.Boolean, - Tooltip = "Se la barra a sinistra parte con le etichette estese (256 px) o con le sole icone (80 px). Il pulsante del menu la apre e la chiude comunque.", + Path = S + "sessions", + Label = "Fasce orarie di ingresso", + Initial = string.Join(",", s.Sessions.Select(static x => FormattableString.Invariant($"{x.From:00}-{x.To:00}"))), + Kind = SettingKind.List, + Scope = SettingScope.Engine, + AllowEmpty = true, + Suffix = "UTC, HH-HH", + Tooltip = "Fasce orarie UTC in cui sono ammesse le entrate, separate da virgole (es. 07-16,20-22). Vuoto = sempre. Le uscite non hanno orari.", }); return g; } - private static SettingGroup Notifications(BotConfig config) + // ----------------------------------------------------------------------- + // Avanzate + // ----------------------------------------------------------------------- + + private static SettingGroup Advanced(BasketStrategyConfig s) + { + SettingGroup g = new("avanzate", "Strategia ▸ avanzate", + "Sovrascritture del preset, indicatori, finestre e soglie. Ogni numero è documentato in strategy.json; un cambio qui è una decisione " + + "che il forward test giudica, e finisce nel ledger come ogni altro.", + SettingTarget.Strategy, advanced: true); + + BasketPreset p = BasketPresets.Get(s.Preset); + + // Preset overrides: empty = the preset's value (the key leaves the file). + g.Fields.Add(Override(S + "zIn", "zIn (sovrascrive il preset)", s.ZInOverride, p.ZIn, 0.5, 6, SettingKind.Number, string.Empty, + "|z| del cross sintetico oltre il quale si entra.")); + g.Fields.Add(Override(S + "riskPerBasketPct", "Rischio per basket (sovrascrive il preset)", s.RiskPerBasketPctOverride, p.RiskPerBasketPct, 0.01, 5, SettingKind.Number, "% dell'equity", + "Perdita allo stop, in % dell'equity, su cui si calcola la size.")); + g.Fields.Add(Override(S + "maxBaskets", "Basket aperti al massimo (sovrascrive il preset)", s.MaxBasketsOverride > 0 ? s.MaxBasketsOverride : double.NaN, p.MaxBaskets, 1, 10, SettingKind.Integer, string.Empty, + "Quanti basket possono essere aperti insieme.")); + g.Fields.Add(Override(S + "tpPips", "Take-profit (sovrascrive il preset)", s.TpPipsOverride, p.TpPips, 1, 500, SettingKind.Number, "pip di basket", + "Take-profit di basket in pip lordi (somma delle due gambe).")); + g.Fields.Add(Override(S + "maxAdds", "Aggiunte al massimo (sovrascrive il preset)", s.MaxAddsOverride >= 0 ? s.MaxAddsOverride : double.NaN, p.MaxAdds, 0, 5, SettingKind.Integer, string.Empty, + "Aggiunte ammesse per basket quando averagingMode le consente.")); + g.Fields.Add(Override(S + "zStop", "zStop (sovrascrive il preset)", s.ZStopOverride, p.ZStop, 1, 10, SettingKind.Number, string.Empty, + "|z| oltre il quale il basket si chiude in perdita. Deve superare zIn.")); + + // Modes. + g.Fields.Add(Choice(S + "signalMode", "Segnale", s.SignalMode.ToString(), ["ZScoreSynthetic", "PipDivergence"], SettingScope.Engine, + "ZScoreSynthetic (di fabbrica): |z| ≥ zIn sul cross sintetico. PipDivergence: divergenza in pip dall'ancora (dIn), come l'interfaccia Titany.")); + g.Fields.Add(Choice(S + "exitMode", "Uscita", s.ExitMode.ToString(), ["First", "FixedPips", "ZReturn"], SettingScope.Engine, + "First = la prima fra TP in pip e rientro dello z; FixedPips = solo TP in pip; ZReturn = solo |z| ≤ zOut.")); + g.Fields.Add(Choice(S + "averagingMode", "Aggiunte", s.AveragingMode.ToString(), ["Off", "AddOnce", "Grid"], SettingScope.Engine, + "Off di fabbrica; AddOnce ammette una sola aggiunta, Grid fino al massimo del preset. Moltiplicatore di lotto sempre 1,0 (niente martingala).")); + g.Fields.Add(Choice(S + "tpMode", "Take-profit", s.TpMode.ToString(), ["Pips", "AtrMultiple"], SettingScope.Engine, + "Pips = TP del preset; AtrMultiple = tpAtrMultiple × ATR della gamba A.")); + g.Fields.Add(Number(S + "tpAtrMultiple", "Multiplo ATR del TP", s.TpAtrMultiple, "× ATR", 0.1, 20, SettingScope.Engine, + "Solo con tpMode = AtrMultiple.")); + g.Fields.Add(Choice(S + "sameCrossPolicy", "Stesso cross sintetico", s.SameCrossPolicy.ToString(), ["Exclusive", "Half"], SettingScope.Engine, + "I basket 4 e 5 sono entrambi EURCAD: Exclusive = uno solo aperto per volta; Half = entrambi a metà size.")); + + // Indicators and windows. + g.Fields.Add(Integer(S + "window", "Finestra", s.Window, "barre M15", 20, 2000, SettingScope.Engine, + "Finestra di correlazione ρ_W e dello z-score del cross sintetico. Deve superare windowShort.")); + g.Fields.Add(Integer(S + "windowShort", "Finestra corta", s.WindowShort, "barre M15", 5, 1999, SettingScope.Engine, + "Finestra della correlazione breve ρ_20, che segnala una correlazione rotta di recente.")); + g.Fields.Add(Number(S + "rhoMin", "Correlazione minima ρ_W", s.RhoMin, string.Empty, 0, 1, SettingScope.Engine, + "|ρ_W| minimo, con il segno atteso, per entrare.")); + g.Fields.Add(Number(S + "rhoShortMin", "Correlazione breve minima", s.RhoShortMin, string.Empty, 0, 1, SettingScope.Engine, + "|ρ_20| minimo per entrare.")); + g.Fields.Add(Number(S + "halfLifeMinBars", "Half-life minima", s.HalfLifeMinBars, "barre", 1, 1000, SettingScope.Engine, + "Half-life OLS dello spread sotto la quale non si entra (rumore).")); + g.Fields.Add(Number(S + "halfLifeMaxBars", "Half-life massima", s.HalfLifeMaxBars, "barre", 2, 5000, SettingScope.Engine, + "Half-life sopra la quale non si entra (il ritorno alla media è troppo lento).")); + g.Fields.Add(Integer(S + "halfLifeRecalcHours", "Ricalcolo half-life ogni", s.HalfLifeRecalcHours, "ore", 1, 168, SettingScope.Engine, + "Ogni quanto si ricalcola la half-life di un basket.")); + g.Fields.Add(Integer(S + "atrPeriod", "Periodo ATR", s.AtrPeriod, "barre", 2, 500, SettingScope.Engine, + "Periodo dell'ATR usato dal sizing a parità di volatilità.")); + g.Fields.Add(Integer(S + "ewmaSpan", "Span EWMA", s.EwmaSpan, "barre", 2, 5000, SettingScope.Engine, + "Span della volatilità EWMA del cross.")); + g.Fields.Add(Integer(S + "trendPeriod", "Periodo del trend", s.TrendPeriod, "barre", 2, 500, SettingScope.Engine, + "Periodo della forza del trend del cross (una feature del modello).")); + + // Thresholds. + g.Fields.Add(Number(S + "zOut", "zOut", s.ZOut, string.Empty, 0, 5, SettingScope.Engine, + "|z| sotto il quale il basket è rientrato (uscita per convergenza).")); + g.Fields.Add(Number(S + "dIn", "dIn (PipDivergence)", s.DIn, "pip", 1, 500, SettingScope.Engine, + "Solo con signalMode = PipDivergence: divergenza in pip dall'ancora che apre un basket.")); + g.Fields.Add(Integer(S + "anchorBars", "Barre fra due ancore", s.AnchorBars, "barre", 1, 2000, SettingScope.Engine, + "Solo con signalMode = PipDivergence: ogni quante barre l'ancora si azzera.")); + g.Fields.Add(Number(S + "gridStepZ", "Passo delle aggiunte", s.GridStepZ, "z", 0.05, 5, SettingScope.Engine, + "|z| deve crescere di tanto dall'ultima entrata per un'aggiunta.")); + g.Fields.Add(new SettingField + { + Path = S + "lotMultiplier", + Label = "Moltiplicatore di lotto", + Initial = N(s.LotMultiplier), + Kind = SettingKind.Number, + IsReadOnly = true, + ReadOnlyReason = "nel bot vale sempre 1,0 (niente martingala); valori fino a 1,5 servono solo al test di falsificazione del backtest", + Tooltip = "Moltiplicatore della size di ogni aggiunta.", + }); + g.Fields.Add(Number(S + "rhoBreak", "Correlazione rotta sotto", s.RhoBreak, "|ρ_20|", 0, 1, SettingScope.Engine, + "|ρ_20| sotto questa soglia per rhoBreakBars barre chiude il basket aperto.")); + g.Fields.Add(Integer(S + "rhoBreakBars", "Barre di correlazione rotta", s.RhoBreakBars, "barre", 1, 500, SettingScope.Engine, + "Quante chiusure di barra di fila con la correlazione rotta prima di chiudere.")); + g.Fields.Add(Integer(S + "maxHoldingBars", "Durata massima", s.MaxHoldingBars, "barre (96 = 24 h)", 1, 5000, SettingScope.Engine, + "Time-stop: oltre queste barre il basket si chiude comunque. Vale anche per i basket aperti.")); + g.Fields.Add(Number(S + "slippagePipsPerLeg", "Slippage per gamba (backtest)", s.SlippagePipsPerLeg, "pip", 0, 10, SettingScope.Engine, + "Usato dal backtest; il bot misura lo slippage reale di ogni ordine.")); + + // Sizing and runtime limits. + g.Fields.Add(Number(S + "maxEffectiveLeverage", "Leva effettiva massima", s.MaxEffectiveLeverage, "×", 0.1, 30, SettingScope.Engine, + "Nozionale complessivo del basket diviso l'equity, al massimo.")); + g.Fields.Add(Integer(S + "orderLeverage", "Leva degli ordini", s.OrderLeverage, "×", 1, 30, SettingScope.Engine, + "Leva dichiarata a eToro per ogni gamba (1, 2, 5, 10, 20, 30: se lo strumento non la ammette si usa la più vicina consentita).")); + g.Fields.Add(Number(S + "volScaleMin", "Scala di volatilità minima", s.VolScaleMin, "×", 0.1, 5, SettingScope.Engine, + "zIn effettivo = zIn × clamp(σ prevista / σ media 30 g, volScaleMin, volScaleMax).")); + g.Fields.Add(Number(S + "volScaleMax", "Scala di volatilità massima", s.VolScaleMax, "×", 0.1, 5, SettingScope.Engine, + "Vedi la scala minima.")); + g.Fields.Add(Integer(S + "volAverageDays", "Media di volatilità su", s.VolAverageDays, "giorni", 1, 365, SettingScope.Engine, + "Giorni della σ media con cui si confronta la previsione.")); + g.Fields.Add(Number(S + "mlMinProbability", "Probabilità minima del cancello ML", s.MlMinProbability, string.Empty, 0, 1, SettingScope.Engine, + "Con il cancello ML attivo, sotto questa p_ML non si entra.")); + g.Fields.Add(Integer(S + "legTimeoutSec", "Timeout della gamba", s.LegTimeoutSec, "secondi", 1, 120, SettingScope.Engine, + "Attesa dell'esito di una gamba prima di lasciarla nel registro degli ordini e mettere il basket in attesa.")); + g.Fields.Add(Integer(S + "clockSkewMaxSeconds", "Scarto massimo dell'orologio", s.ClockSkewMaxSeconds, "secondi", 1, 300, SettingScope.Engine, + "Oltre questo scarto fra l'orologio locale e quello di eToro le entrate si bloccano.")); + + // Structure: only a fresh engine can take it. + g.Fields.Add(Bool(S + "preferDirectCross", "Legge anche i cross diretti", s.PreferDirectCross, SettingScope.Restart, + "Legge anche le quotazioni dei cross diretti (EURCHF, EURCAD…) quando eToro li quota. Cambia gli strumenti del motore: lo riavvia.")); + for (int i = 0; i < s.Baskets.Count; i++) + { + BasketDefinition d = s.Baskets[i]; + g.Fields.Add(Pair(FormattableString.Invariant($"{S}baskets[{i}].a"), FormattableString.Invariant($"Basket {i + 1}: coppia A"), d.A)); + g.Fields.Add(Pair(FormattableString.Invariant($"{S}baskets[{i}].b"), FormattableString.Invariant($"Basket {i + 1}: coppia B"), d.B)); + } + + return g; + } + + private static SettingField Pair(string path, string label, string value) => new() + { + Path = path, + Label = label, + Initial = value, + Kind = SettingKind.Text, + Scope = SettingScope.Restart, + Tooltip = "Codice a sei lettere della coppia (es. EURUSD). Le due coppie di un basket devono avere una valuta in comune: il cross sintetico " + + "e il verso delle gambe sono derivati. Cambiarla è rifiutato con basket aperti o ordini in sospeso e riavvia il motore.", + }; + + // ----------------------------------------------------------------------- + // Notifiche Telegram + // ----------------------------------------------------------------------- + + private static SettingGroup Telegram(BotConfig config) { Core.Notifications.TelegramOptions t = config.Notifications.Telegram; - SettingGroup g = new( - "Notifiche", - "Telegram: stato ogni ora, eventi, riepilogo giornaliero e comandi dalla chat autorizzata. Il token del bot va nella variabile " + - "d'ambiente TELEGRAM_BOT_TOKEN (mai in un file); il chat id qui o in TELEGRAM_CHAT_ID."); - - g.Fields.Add(new SettingField - { - Path = "notifications.telegram.enabled", - Label = "Telegram attivo", - Initial = t.Enabled ? "sì" : "no", - Kind = SettingKind.Boolean, - Tooltip = "Con 'sì' e un token nell'ambiente il bot manda le notifiche alla chat indicata e ne accetta i comandi.", - }); + SettingGroup g = new("telegram", "Notifiche Telegram", + "Stato ogni ora, eventi, riepilogo giornaliero e comandi dalla chat autorizzata. Il token del bot si inserisce qui sotto e resta cifrato; " + + "ogni cambio vale subito.", + SettingTarget.Config); + g.Fields.Add(Bool("notifications.telegram.enabled", "Telegram attivo", t.Enabled, SettingScope.Immediate, + "Acceso, con un token e un chat id, il bot manda le notifiche alla chat indicata e ne accetta i comandi.")); g.Fields.Add(new SettingField { Path = "notifications.telegram.chatId", @@ -248,102 +456,126 @@ public static class SettingsCatalogue AllowEmpty = true, Tooltip = "L'id numerico della chat (scrivi al bot @userinfobot per conoscere il tuo). Solo questa chat riceve i messaggi e può dare comandi.", }); - - g.Fields.Add(new SettingField - { - Path = "notifications.telegram.hourlyStatus", - Label = "Stato ogni ora", - Initial = t.HourlyStatus ? "sì" : "no", - Kind = SettingKind.Boolean, - Tooltip = "Allo scoccare di ogni ora UTC: equity, P&L, basket aperti, orfane, drawdown, prossimo evento, stato API.", - }); - - g.Fields.Add(new SettingField - { - Path = "notifications.telegram.eventAlerts", - Label = "Eventi", - Initial = t.EventAlerts ? "sì" : "no", - Kind = SettingKind.Boolean, - Tooltip = "Apertura e chiusura dei basket, ordini risolti, kill-switch, equity stop, recupero, errori persistenti.", - }); - - g.Fields.Add(new SettingField - { - Path = "notifications.telegram.dailySummaryUtcHour", - Label = "Riepilogo giornaliero alle", - Initial = t.DailySummaryUtcHour.ToString(CultureInfo.CurrentCulture), - Kind = SettingKind.Integer, - Suffix = "ora UTC (−1 = spento)", - Minimum = -1, - Maximum = 23, - Tooltip = "P&L del giorno, numero di basket, win rate, costi, drawdown.", - }); - - g.Fields.Add(new SettingField - { - Path = "notifications.telegram.commands", - Label = "Comandi dalla chat", - Initial = t.Commands ? "sì" : "no", - Kind = SettingKind.Boolean, - Tooltip = "/stato, /posizioni, /storico 7d, /pausa, /riprendi, /chiudi , /kill CONFERMO, /reset . Ogni comando finisce nel ledger.", - }); + g.Fields.Add(Bool("notifications.telegram.hourlyStatus", "Stato ogni ora", t.HourlyStatus, SettingScope.Immediate, + "Allo scoccare di ogni ora UTC: equity, P&L, basket aperti, orfane, drawdown, prossimo evento, stato API.")); + g.Fields.Add(Bool("notifications.telegram.eventAlerts", "Eventi", t.EventAlerts, SettingScope.Immediate, + "Apertura e chiusura dei basket, ordini risolti, kill-switch, equity stop, recupero, errori persistenti. Gli allarmi partono comunque.")); + g.Fields.Add(Integer("notifications.telegram.dailySummaryUtcHour", "Riepilogo giornaliero alle", t.DailySummaryUtcHour, "ora UTC (−1 = spento)", -1, 23, SettingScope.Immediate, + "P&L del giorno, numero di basket, win rate, costi, drawdown.")); + g.Fields.Add(Bool("notifications.telegram.commands", "Comandi dalla chat", t.Commands, SettingScope.Immediate, + "/stato, /posizioni, /storico 7d, /pausa, /riprendi, /chiudi , /kill CONFERMO, /reset . Ogni comando finisce nel ledger.")); return g; } + // ----------------------------------------------------------------------- + // Interfaccia + // ----------------------------------------------------------------------- + + private static SettingGroup Interface(BotConfig config) + { + SettingGroup g = new("interfaccia", "Interfaccia", + "Come l'interfaccia mostra le cose. Niente qui cambia quello che il bot fa. Gli orologi usano il fuso del browser.", + SettingTarget.Config); + + g.Fields.Add(Choice("ui.displayCurrency", "Valuta di visualizzazione", config.Ui.DisplayCurrency, UiOptions.Currencies, SettingScope.Immediate, + "La valuta in cui l'interfaccia mostra gli importi. I tassi vengono dalle quotazioni eToro già in polling; ogni importo convertito porta nel " + + "tooltip il valore in USD e il tasso usato. Ledger, baskets.csv, Telegram e ogni decisione restano in USD.")); + g.Fields.Add(Choice("ui.theme", "Tema", config.Ui.Theme, ["dark", "light"], SettingScope.Immediate, + "Palette scura (predefinita) o chiara.")); + g.Fields.Add(Bool("ui.navExpanded", "Barra di navigazione aperta", config.Ui.NavExpanded, SettingScope.Immediate, + "Se la barra a sinistra parte con le etichette o con le sole icone. Il pulsante del menu la apre e la chiude comunque.")); + + return g; + } + + // ----------------------------------------------------------------------- + // Log + // ----------------------------------------------------------------------- + private static SettingGroup Logging(BotConfig config) { - SettingGroup g = new( - "Registrazione", - "Il log dell'applicazione. Il ledger delle decisioni e dei basket sta in data/ledger e non si configura."); + SettingGroup g = new("log", "Log", + "Il log dell'applicazione. Il ledger delle decisioni e dei basket sta in data/ledger e non si configura. Ogni cambio vale subito.", + SettingTarget.Config); - g.Fields.Add(new SettingField - { - Path = "logging.level", - Label = "Dettaglio del log", - Initial = config.Logging.Level, - Kind = SettingKind.Choice, - Choices = ["trace", "debug", "info", "warn", "error", "none"], - Tooltip = "'info' basta: ogni rifiuto che impedisce un ordine viene scritto a questo livello o sopra, " + - "con il basket e il motivo esatto.", - }); - - g.Fields.Add(new SettingField - { - Path = "logging.maxFileSizeMb", - Label = "Dimensione massima del log", - Initial = config.Logging.MaxFileSizeMb.ToString(CultureInfo.CurrentCulture), - Kind = SettingKind.Integer, - Suffix = "MB (0 = nessuna rotazione)", - Minimum = 0, - Maximum = 4096, - Tooltip = "Superata questa dimensione il file viene ruotato: encelado.1.log, encelado.2.log e così via.", - }); - - g.Fields.Add(new SettingField - { - Path = "logging.maxFiles", - Label = "File di log conservati", - Initial = config.Logging.MaxFiles.ToString(CultureInfo.CurrentCulture), - Kind = SettingKind.Integer, - Suffix = "file ruotati", - Minimum = 1, - Maximum = 500, - Tooltip = "Quanti file ruotati tenere prima di cancellare il più vecchio.", - }); - - g.Fields.Add(new SettingField - { - Path = "logging.bufferedLines", - Label = "Righe tenute in memoria", - Initial = config.Logging.BufferedLines.ToString(CultureInfo.CurrentCulture), - Kind = SettingKind.Integer, - Suffix = "righe", - Minimum = 100, - Maximum = 200_000, - Tooltip = "Quante righe tiene la scheda Log. Il file su disco resta completo comunque.", - }); + g.Fields.Add(Choice("logging.level", "Dettaglio del log", config.Logging.Level.Trim().ToLowerInvariant(), ["trace", "debug", "info", "warn", "error", "none"], SettingScope.Immediate, + "'info' basta: ogni rifiuto che impedisce un ordine viene scritto a questo livello o sopra, con il basket e il motivo esatto.")); + g.Fields.Add(Integer("logging.maxFileSizeMb", "Dimensione massima del log", config.Logging.MaxFileSizeMb, "MB (0 = nessuna rotazione)", 0, 4096, SettingScope.Immediate, + "Superata questa dimensione il file viene ruotato: encelado.1.log, encelado.2.log e così via.")); + g.Fields.Add(Integer("logging.maxFiles", "File di log conservati", config.Logging.MaxFiles, "file ruotati", 1, 500, SettingScope.Immediate, + "Quanti file ruotati tenere prima di cancellare il più vecchio.")); + g.Fields.Add(Integer("logging.statusLines", "Righe di attività in dashboard", config.Logging.StatusLines, "righe", 20, 5000, SettingScope.Immediate, + "Quante righe tiene la striscia di attività della dashboard.")); + g.Fields.Add(Integer("logging.bufferedLines", "Righe tenute in memoria", config.Logging.BufferedLines, "righe", 100, 200_000, SettingScope.Immediate, + "Quante righe tiene la pagina Log (almeno quante quelle della dashboard). Il file su disco resta completo comunque.")); return g; } + + // ----------------------------------------------------------------------- + // Field builders + // ----------------------------------------------------------------------- + + private static SettingField Bool(string path, string label, bool value, SettingScope scope, string tooltip) => new() + { + Path = path, + Label = label, + Initial = B(value), + Kind = SettingKind.Boolean, + Scope = scope, + Tooltip = tooltip, + }; + + private static SettingField Choice(string path, string label, string value, IReadOnlyList choices, SettingScope scope, string tooltip) => new() + { + Path = path, + Label = label, + Initial = choices.FirstOrDefault(c => c.Equals(value, StringComparison.OrdinalIgnoreCase)) ?? value, + Kind = SettingKind.Choice, + Choices = choices, + Scope = scope, + Tooltip = tooltip, + }; + + private static SettingField Number(string path, string label, double value, string suffix, double min, double max, SettingScope scope, string tooltip) => new() + { + Path = path, + Label = label, + Initial = N(value), + Kind = SettingKind.Number, + Suffix = suffix, + Minimum = min, + Maximum = max, + Scope = scope, + Tooltip = tooltip, + }; + + private static SettingField Integer(string path, string label, int value, string suffix, int min, int max, SettingScope scope, string tooltip) => new() + { + Path = path, + Label = label, + Initial = I(value), + Kind = SettingKind.Integer, + Suffix = suffix, + Minimum = min, + Maximum = max, + Scope = scope, + Tooltip = tooltip, + }; + + /// A preset override: empty (the key absent from the file) means the preset's own value. + private static SettingField Override(string path, string label, double value, double presetValue, double min, double max, SettingKind kind, string suffix, string what) => new() + { + Path = path, + Label = label, + Initial = double.IsFinite(value) ? N(value) : string.Empty, + Kind = kind, + Suffix = suffix, + Minimum = min, + Maximum = max, + AllowEmpty = true, + Scope = SettingScope.Engine, + Tooltip = $"{what} Vuoto = il valore del preset ({N(presetValue)}). Vale per i basket nuovi.", + }; } diff --git a/Encelado/src/Encelado.Engine/Settings/SettingsRuntime.cs b/Encelado/src/Encelado.Engine/Settings/SettingsRuntime.cs new file mode 100644 index 0000000..fffb9ae --- /dev/null +++ b/Encelado/src/Encelado.Engine/Settings/SettingsRuntime.cs @@ -0,0 +1,811 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; +using Encelado.Core.Baskets; +using Encelado.Core.Broker; +using Encelado.Core.Notifications; +using Encelado.Engine.Configuration; +using Encelado.Engine.Logging; +using Encelado.Etoro; + +namespace Encelado.Engine.Settings; + +/// What the host applies itself after a save, and how keys and tokens are proved before they are stored. +public sealed class SettingsHooks +{ + /// The process-level reconfiguration: log level and rotation, the log window's size, the clock. + public Action? ReconfigureProcess { get; init; } + + /// Brings the notifier in line with the settings and the stored token (switch on/off, new token, commands). + public Func? ReconfigureNotifier { get; init; } + + /// The history page reads with the new keys or account from the next request. + public Action? InvalidateHistory { get; init; } + + /// Proves a pair of keys on the account the options name; returns what it found ("utente …, equity …"), throws when refused. + public Func>? VerifyEtoroKeys { get; init; } + + /// Proves a Telegram token (getMe); returns the bot's name, throws when refused. + public Func>? VerifyTelegramToken { get; init; } + + /// Sends one test message to the configured chat. + public Func>? SendTelegramTest { get; init; } +} + +/// What happened to one saved path. +public sealed record SettingsPathResult(string Path, string Applied, string Message); + +/// The answer of POST /api/settings (docs/API.md). +public sealed record SettingsResult(bool Ok, string Message, IReadOnlyList Results, string Restart, IReadOnlyDictionary Errors) +{ + public const string RestartNone = "none"; + public const string RestartDone = "done"; + public const string RestartNeedsPhrase = "needsPhrase"; + public const string RestartRefused = "refused"; + + public int HttpStatus => Restart is RestartNeedsPhrase or RestartRefused ? 409 : Ok ? 200 : 400; +} + +/// The answer of the secret routes (keys, token, unlock, reset, restore). +public sealed record SecretActionResult(bool Ok, string Message, string Restart = SettingsResult.RestartNone, int HttpStatus = 200) +{ + /// A detail the page can show: the backup path, the account the keys are for. + public string Detail { get; init; } = string.Empty; +} + +/// +/// The settings of the running bot (5.1, decision C11): every save is applied by the bot +/// without a restart when possible. +/// +/// One lock serialises every write (the settings page, the keys, the restore, AVVIA). A +/// save validates each touched file as a whole on a copy, writes it atomically (strategy +/// first), copies the file into the one shared +/// () and applies what can be applied at once: log, +/// log window, activity feed, notifier, history. Engine-scoped changes reach the running +/// engine as an command executed on its +/// decision thread. Restart-scoped changes (the account, the pairs, the direct crosses) +/// stop the engine without closing a basket and start it again — never into Live without +/// the phrase: a save that would restart a Live engine is answered 409 needsPhrase +/// before anything is written, and a change of account is refused while baskets or orders +/// are open (). +/// +/// +/// The secrets live in the ; keys are proved on their own +/// account before they are saved, the Telegram token with getMe. +/// +/// +public sealed class SettingsRuntime +{ + private readonly SemaphoreSlim _lock = new(1, 1); + private readonly SettingsHooks _hooks; + private long _version = 1; + + public SettingsRuntime(BotConfig config, string configPath, SecretStore secrets, BotSupervisor supervisor, SettingsHooks? hooks = null) + { + Config = config ?? throw new ArgumentNullException(nameof(config)); + ArgumentException.ThrowIfNullOrWhiteSpace(configPath); + ConfigPath = configPath; + Secrets = secrets ?? throw new ArgumentNullException(nameof(secrets)); + Supervisor = supervisor ?? throw new ArgumentNullException(nameof(supervisor)); + _hooks = hooks ?? new SettingsHooks(); + Strategy = new StrategyCache(config.Run.StrategyPath); + supervisor.StrategyProvider ??= Strategy.Current; + supervisor.HostStatusProvider ??= () => new HostStatus(Secrets.StateName, Import.Ignored); + } + + /// The shared configuration, kept equal to the file after every save. + public BotConfig Config { get; } + + public string ConfigPath { get; } + + /// strategy.json, cached. + public StrategyCache Strategy { get; } + + public SecretStore Secrets { get; } + + public BotSupervisor Supervisor { get; } + + /// What the one-time import did (the ignored variables and its note). + public ImportOutcome Import { get; set; } = ImportOutcome.Nothing; + + /// Where the interface password comes from: ENCELADO_PASSWORD, ENCELADO_WEB_TOKEN or none. + public string PasswordSource { get; set; } = InterfacePassword.NoSource; + + /// A number that changes at every save (settings or secrets): the page reloads the settings only then. + public long Version => Interlocked.Read(ref _version); + + // ----------------------------------------------------------------------- + // Reading + // ----------------------------------------------------------------------- + + /// The answer of GET /api/settings: the catalogue with the values of the files, the engine, the secrets. + public string Describe() + { + BotConfig file = ConfigFromFileOrMemory(); + IReadOnlyList groups = SettingsCatalogue.Build(file, Strategy.Current()); + using MemoryStream ms = new(); + using (Utf8JsonWriter w = new(ms)) + { + w.WriteStartObject(); + w.WriteString("configPath", ConfigPath); + w.WriteString("strategyPath", Strategy.Path); + w.WriteNumber("version", Version); + w.WriteStartObject("engine"); + w.WriteString("state", Supervisor.State.ToString().ToLowerInvariant()); + w.WriteString("account", Config.Run.Mode.Account()); + w.WriteBoolean("running", Supervisor.IsRunning); + w.WriteEndObject(); + SettingsService.WriteGroups(w, groups); + SettingsService.WriteSecrets(w, "secrets", DescribeSecrets()); + w.WriteEndObject(); + } + + return Encoding.UTF8.GetString(ms.ToArray()); + } + + public SecretsSummary DescribeSecrets() => new( + Secrets.StateName, + Secrets.DescribeEtoro(demo: true), + Secrets.DescribeEtoro(demo: false), + Secrets.DescribeTelegram(), + PasswordSource, + Import.Ignored, + Import.Note, + Secrets.Problem); + + // ----------------------------------------------------------------------- + // Saving settings + // ----------------------------------------------------------------------- + + /// Validates, writes and applies a batch of edits (POST /api/settings). + public async Task ApplyAsync(IReadOnlyDictionary edits, string? confirm, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(edits); + if (edits.Count == 0) + { + return new SettingsResult(false, "nessuna modifica", [], SettingsResult.RestartNone, new Dictionary()); + } + + await _lock.WaitAsync(ct).ConfigureAwait(false); + try + { + return await ApplyCoreAsync(edits, confirm, ct).ConfigureAwait(false); + } + finally + { + _lock.Release(); + } + } + + private async Task ApplyCoreAsync(IReadOnlyDictionary edits, string? confirm, CancellationToken ct) + { + BotConfig fileConfig; + BasketStrategyConfig fileStrategy; + try + { + fileConfig = ConfigLoader.Load(ConfigPath, out _); + fileStrategy = BasketStrategyConfig.Load(Strategy.Path, out _); + } + catch (Exception ex) when (ex is IOException or JsonException or InvalidOperationException or UnauthorizedAccessException) + { + return Failure($"i file delle impostazioni non sono leggibili: {ex.Message}"); + } + + SettingsPlan plan = SettingsService.Plan(SettingsCatalogue.Build(fileConfig, fileStrategy), edits); + if (plan.Errors.Count > 0) + { + return new SettingsResult(false, "valori non validi: " + string.Join("; ", plan.Errors.Select(static e => $"{e.Key}: {e.Value}")), [], SettingsResult.RestartNone, plan.Errors); + } + + if (plan.Changed.Count == 0) + { + return new SettingsResult(true, "nessun valore diverso da quello salvato", [], SettingsResult.RestartNone, new Dictionary()); + } + + (BotConfig? next, _, string? invalid) = SettingsService.Validate(ConfigPath, Strategy.Path, plan); + if (invalid is not null || next is null) + { + return new SettingsResult(false, invalid ?? "configurazione non valida", [], SettingsResult.RestartNone, new Dictionary { ["*"] = invalid ?? "configurazione non valida" }); + } + + ExecutionMode before = Config.Run.Mode; + ExecutionMode after = next.Run.Mode; + bool running = Supervisor.IsRunning; + bool confirmed = LiveConfirmation.IsConfirmed(confirm); + List restartFields = [.. plan.Changed.Values.Where(static f => f.Scope == SettingScope.Restart)]; + bool accountChange = before != after; + bool pairsChange = plan.Changed.Values.Any(static f => f.Target == SettingTarget.Strategy && f.FilePath.StartsWith("baskets[", StringComparison.Ordinal) && !f.FilePath.EndsWith(".enabled", StringComparison.Ordinal)); + + // The guards come before any write: a refused save changes nothing. + if (accountChange || pairsChange) + { + AccountActivity activity = running ? AccountActivity.FromSnapshot(Supervisor.Snapshot()) : AccountActivity.FromDisk(Config.Run.DataPath); + if (activity.Busy) + { + string what = accountChange ? "il cambio di conto" : "il cambio delle coppie dei basket"; + return Refused($"{what} è rifiutato: sul conto ci sono {activity.Describe()}. Chiudili (anche con il kill-switch) e riprova."); + } + } + + if (accountChange && running && Secrets.Etoro(demo: !after.IsLive()) is null) + { + return Refused($"mancano le chiavi del conto {(after.IsLive() ? "reale" : "demo")}: inseriscile prima di cambiare conto a motore acceso"); + } + + if (running && restartFields.Count > 0 && after.IsLive() && !confirmed) + { + return new SettingsResult(false, $"il cambio riavvia il motore sul conto reale: scrivi {LiveConfirmation.Phrase} per confermare (niente è stato salvato)", + [.. restartFields.Select(static f => new SettingsPathResult(f.Path, "error", $"serve {LiveConfirmation.Phrase}"))], SettingsResult.RestartNeedsPhrase, new Dictionary()); + } + + try + { + SettingsService.Write(ConfigPath, Strategy.Path, plan); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException) + { + return Failure($"salvataggio non riuscito: {ex.Message}"); + } + + await RefreshMemoryAsync(plan.Changed.Keys, accountChange).ConfigureAwait(false); + + // The running engine. + string restart = SettingsResult.RestartNone; + bool engineOk = true; + string engineMessage = string.Empty; + if (running) + { + string paths = string.Join(", ", plan.Changed.Keys); + if (restartFields.Count > 0) + { + CommandResult r = await RestartCoreAsync(confirmed, $"impostazioni salvate: {paths}").ConfigureAwait(false); + restart = SettingsResult.RestartDone; + engineOk = r.Ok; + engineMessage = r.Message; + } + else if (plan.Changed.Values.Any(static f => f.Scope == SettingScope.Engine)) + { + CommandResult r = await ApplyToEngineAsync(plan.Changed.Keys, ct).ConfigureAwait(false); + if (!r.Ok && r.Code == CommandResult.RestartRequired) + { + // strategy.json changed what a running engine cannot take (edited by hand as well). + if (Supervisor.RunningLive && !confirmed) + { + engineOk = false; + engineMessage = $"la strategia cambia i basket: serve un riavvio, premi FERMA e poi AVVIA con {LiveConfirmation.Phrase}"; + } + else + { + r = await RestartCoreAsync(confirmed, $"strategia cambiata: {paths}").ConfigureAwait(false); + restart = SettingsResult.RestartDone; + engineOk = r.Ok; + engineMessage = r.Message; + } + } + else + { + engineOk = r.Ok; + engineMessage = r.Message; + } + } + } + + List results = []; + foreach (SettingField f in plan.Changed.Values) + { + results.Add(Result(f, running, restart, engineOk, engineMessage)); + } + + bool ok = results.All(static r => r.Applied != "error"); + string summary = restart == SettingsResult.RestartDone + ? (engineOk ? $"{Saved(results.Count)}; motore riavviato (i basket aperti restano)" : $"{Saved(results.Count)}; il motore si è fermato ma non è ripartito: {engineMessage}") + : $"{Saved(results.Count)}: " + string.Join(", ", new[] + { + Part(results.Count(static r => r.Applied == "immediate"), "applicato subito", "applicati subito"), + Part(results.Count(static r => r.Applied == "engine"), "applicato al motore", "applicati al motore"), + Part(results.Count(static r => r.Applied == "stored"), "valido dal prossimo avvio del motore", "validi dal prossimo avvio del motore"), + }.Where(static p => p.Length > 0)) + (ok ? string.Empty : $" — {engineMessage}"); + Log.Info($"impostazioni: {summary} ({string.Join(", ", plan.Changed.Keys)})"); + return new SettingsResult(ok, summary, results, restart, new Dictionary()); + } + + /// How long a save waits for the engine to take it; past that it stays queued and is applied when the engine is free. + private static readonly TimeSpan EngineApplyWait = TimeSpan.FromSeconds(20); + + /// + /// Hands the change to the engine's decision thread. An engine still warming up (the + /// first minute after a start) drains its commands only when its loop begins: the + /// command stays queued and is applied then, and the page is not kept waiting. + /// + private async Task ApplyToEngineAsync(IEnumerable paths, CancellationToken ct) + { + using CancellationTokenSource wait = CancellationTokenSource.CreateLinkedTokenSource(ct); + wait.CancelAfter(EngineApplyWait); + try + { + return await Supervisor.ApplySettingsAsync(paths, "impostazioni dalla web UI", wait.Token).ConfigureAwait(false); + } + catch (Exception ex) when (ex is OperationCanceledException or TimeoutException && !ct.IsCancellationRequested) + { + Log.Info("impostazioni in coda: il motore le applica appena finisce ciò che sta facendo (avvio o riscaldamento)"); + return new CommandResult(true, "in coda: il motore le applica appena libero"); + } + } + + private static string Saved(int n) => n == 1 ? "1 valore salvato" : string.Create(CultureInfo.InvariantCulture, $"{n} valori salvati"); + + private static string Part(int n, string one, string many) => n switch + { + 0 => string.Empty, + 1 => $"1 {one}", + _ => string.Create(CultureInfo.InvariantCulture, $"{n} {many}"), + }; + + private static SettingsPathResult Result(SettingField f, bool running, string restart, bool engineOk, string engineMessage) + { + if (f.Scope == SettingScope.Immediate) + { + return new SettingsPathResult(f.Path, "immediate", f.Path == "run.autostart" ? "salvato: vale al prossimo avvio del container" : "applicato"); + } + + if (!running) + { + return new SettingsPathResult(f.Path, "stored", "salvato (effetto al prossimo avvio del motore)"); + } + + if (!engineOk) + { + return new SettingsPathResult(f.Path, "error", engineMessage); + } + + return restart == SettingsResult.RestartDone + ? new SettingsPathResult(f.Path, "restart", "motore riavviato") + : new SettingsPathResult(f.Path, "engine", engineMessage.StartsWith("in coda", StringComparison.Ordinal) ? engineMessage : "applicato al motore"); + } + + /// The live configuration takes the file; the process-level things follow at once. + private async Task RefreshMemoryAsync(IEnumerable changedPaths, bool accountChange) + { + try + { + Config.CopyFrom(ConfigLoader.Load(ConfigPath, out _)); + } + catch (Exception ex) when (ex is IOException or JsonException or InvalidOperationException or UnauthorizedAccessException) + { + Log.Warn($"impostazioni salvate ma non rilette ({ex.Message}): valgono al prossimo avvio"); + } + + Strategy.Invalidate(); + Interlocked.Increment(ref _version); + _hooks.ReconfigureProcess?.Invoke(Config); + Supervisor.SetEventCapacity(Config.Logging.StatusLines); + if (changedPaths.Any(static p => p.StartsWith("notifications.", StringComparison.OrdinalIgnoreCase))) + { + await ReconfigureNotifierAsync().ConfigureAwait(false); + } + + if (accountChange) + { + _hooks.InvalidateHistory?.Invoke(); + } + } + + private async Task ReconfigureNotifierAsync() + { + if (_hooks.ReconfigureNotifier is { } reconfigure) + { + try + { + await reconfigure().ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + Log.Warn($"notifiche non riconfigurate: {ex.Message}"); + } + } + } + + // ----------------------------------------------------------------------- + // The engine + // ----------------------------------------------------------------------- + + /// + /// AVVIA: the secrets must be open and hold the keys of the account the mode trades on; + /// Live needs = CONFERMO LIVE, typed by a person for this + /// start (answered with otherwise). + /// + public async Task StartEngineAsync(string? confirm) + { + await _lock.WaitAsync().ConfigureAwait(false); + try + { + bool confirmed = LiveConfirmation.IsConfirmed(confirm); + if (Config.Run.Mode.IsLive()) + { + if (!confirmed) + { + return new CommandResult(false, $"la modalità Live parte solo con la frase {LiveConfirmation.Phrase} scritta ora") { Code = CommandResult.NeedsPhrase }; + } + + Log.Warn("avvio in Live sul conto REALE confermato con la frase"); + } + + return await StartCoreAsync(confirmed).ConfigureAwait(false); + } + finally + { + _lock.Release(); + } + } + + private async Task StartCoreAsync(bool liveConfirmed) + { + if (Secrets.State == SecretStoreState.Locked) + { + return new CommandResult(false, $"chiavi non leggibili: {Secrets.Problem}. Sblocca i segreti con la password precedente o ricomincia da Impostazioni ▸ Conto"); + } + + bool live = Config.Run.Mode.IsLive(); + if (Secrets.Etoro(demo: !live) is null) + { + return new CommandResult(false, $"nessuna chiave eToro per il conto {(live ? "reale" : "demo")}: inseriscile da Impostazioni ▸ Conto"); + } + + if (live && !liveConfirmed) + { + return new CommandResult(false, $"la modalità Live parte solo con la frase {LiveConfirmation.Phrase}") { Code = CommandResult.NeedsPhrase }; + } + + return await Supervisor.StartAsync(liveConfirmed: live && liveConfirmed).ConfigureAwait(false); + } + + /// Stops without closing a basket and starts again; the new engine takes the baskets over from the state. + private async Task RestartCoreAsync(bool liveConfirmed, string reason) + { + Log.Info($"riavvio automatico del motore: {reason}"); + await Supervisor.StopAsync(closeBaskets: false).ConfigureAwait(false); + CommandResult started = await StartCoreAsync(liveConfirmed).ConfigureAwait(false); + if (!started.Ok) + { + Log.Warn($"il motore non è ripartito dopo il riavvio automatico: {started.Message}"); + } + + return started; + } + + // ----------------------------------------------------------------------- + // Secrets + // ----------------------------------------------------------------------- + + /// + /// 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). + /// + public async Task SaveKeysAsync(string? account, string? apiKey, string? userKey, string? confirm, CancellationToken ct) + { + if (ParseAccount(account) is not { } demo) + { + return new SecretActionResult(false, "conto sconosciuto: demo oppure live", HttpStatus: 400); + } + + string? api = KeyStores.Clean(apiKey); + string? user = KeyStores.Clean(userKey); + if (api is null || user is null) + { + return new SecretActionResult(false, "servono entrambe le chiavi (x-api-key e x-user-key)", HttpStatus: 400); + } + + if (Secrets.State == SecretStoreState.Locked) + { + return new SecretActionResult(false, $"segreti bloccati ({Secrets.Problem}): sbloccali o ricomincia prima di salvare chiavi", HttpStatus: 409); + } + + string label = demo ? "demo" : "reale"; + bool active = Config.Run.Mode.IsLive() != demo; + bool restart = active && Supervisor.IsRunning; + bool confirmed = LiveConfirmation.IsConfirmed(confirm); + if (restart && !demo && !confirmed) + { + return new SecretActionResult(false, $"le chiavi del conto reale in uso riavviano il motore: scrivi {LiveConfirmation.Phrase} per confermare (niente è stato salvato)", SettingsResult.RestartNeedsPhrase, 409); + } + + EtoroOptions options = new() + { + Environment = demo ? "demo" : "real", + BaseUrl = Config.Etoro.BaseUrl, + RequestTimeoutSeconds = Config.Etoro.RequestTimeoutSeconds, + UserAgent = Config.Etoro.UserAgent, + ApiKey = api, + UserKey = user, + }; + string who; + try + { + who = await (_hooks.VerifyEtoroKeys ?? VerifyEtoroKeysAsync)(options, ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is BrokerException or HttpRequestException or OperationCanceledException or InvalidOperationException or JsonException) + { + return new SecretActionResult(false, $"eToro ha rifiutato le chiavi del conto {label} o non risponde: {ex.Message}", HttpStatus: 400); + } + + await _lock.WaitAsync(ct).ConfigureAwait(false); + try + { + Secrets.SaveEtoro(demo, new EtoroKeys(api, user, DateTime.UtcNow)); + Interlocked.Increment(ref _version); + if (active) + { + _hooks.InvalidateHistory?.Invoke(); + } + + 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"; + if (!restart) + { + return new SecretActionResult(true, message) { Detail = who }; + } + + CommandResult r = await RestartCoreAsync(confirmed, $"nuove chiavi del conto {label}").ConfigureAwait(false); + return new SecretActionResult(r.Ok, r.Ok ? $"{message}; motore riavviato" : $"{message}; il motore non è ripartito: {r.Message}", SettingsResult.RestartDone, r.Ok ? 200 : 500) { Detail = who }; + } + catch (InvalidOperationException ex) + { + return new SecretActionResult(false, ex.Message, HttpStatus: 409); + } + finally + { + _lock.Release(); + } + } + + /// Removes the keys of an account: refused for the account a running engine trades on. + public async Task DeleteKeysAsync(string? account, CancellationToken ct) + { + if (ParseAccount(account) is not { } demo) + { + return new SecretActionResult(false, "conto sconosciuto: demo oppure live", HttpStatus: 400); + } + + await _lock.WaitAsync(ct).ConfigureAwait(false); + try + { + bool active = Config.Run.Mode.IsLive() != demo; + if (active && Supervisor.IsRunning) + { + return new SecretActionResult(false, "sono le chiavi del conto su cui il motore sta lavorando: fermalo prima (o passa all'altro conto)", HttpStatus: 409); + } + + bool removed = Secrets.ClearEtoro(demo); + Interlocked.Increment(ref _version); + if (active) + { + _hooks.InvalidateHistory?.Invoke(); + } + + Log.Info(removed ? $"chiavi eToro del conto {(demo ? "demo" : "reale")} rimosse" : "nessuna chiave da rimuovere"); + return new SecretActionResult(true, removed ? "chiavi rimosse" : "nessuna chiave salvata da rimuovere"); + } + catch (InvalidOperationException ex) + { + return new SecretActionResult(false, ex.Message, HttpStatus: 409); + } + finally + { + _lock.Release(); + } + } + + /// Proves the token with getMe, stores it encrypted and switches the notifier over at once. + public async Task SaveTelegramTokenAsync(string? token, CancellationToken ct) + { + string? clean = KeyStores.Clean(token); + if (clean is null) + { + return new SecretActionResult(false, "serve il token del bot (da @BotFather)", HttpStatus: 400); + } + + if (Secrets.State == SecretStoreState.Locked) + { + return new SecretActionResult(false, $"segreti bloccati ({Secrets.Problem}): sbloccali o ricomincia prima di salvare il token", HttpStatus: 409); + } + + string bot; + try + { + bot = await (_hooks.VerifyTelegramToken ?? VerifyTelegramTokenAsync)(clean, ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException or InvalidOperationException or ArgumentException) + { + return new SecretActionResult(false, $"Telegram ha rifiutato il token o non risponde: {ex.Message}", HttpStatus: 400); + } + + await _lock.WaitAsync(ct).ConfigureAwait(false); + try + { + Secrets.SaveTelegramToken(clean); + Interlocked.Increment(ref _version); + } + catch (InvalidOperationException ex) + { + return new SecretActionResult(false, ex.Message, HttpStatus: 409); + } + finally + { + _lock.Release(); + } + + await ReconfigureNotifierAsync().ConfigureAwait(false); + Log.Info($"token Telegram verificato (@{bot}) e salvato cifrato"); + return new SecretActionResult(true, Config.Notifications.Telegram.Enabled && Config.Notifications.Telegram.ChatId.Length > 0 + ? $"token verificato: @{bot}; Telegram attivo" + : $"token verificato: @{bot}; per usarlo accendi Telegram e scrivi il chat id") { Detail = bot }; + } + + public async Task DeleteTelegramTokenAsync(CancellationToken ct) + { + await _lock.WaitAsync(ct).ConfigureAwait(false); + bool removed; + try + { + removed = Secrets.ClearTelegramToken(); + Interlocked.Increment(ref _version); + } + catch (InvalidOperationException ex) + { + return new SecretActionResult(false, ex.Message, HttpStatus: 409); + } + finally + { + _lock.Release(); + } + + await ReconfigureNotifierAsync().ConfigureAwait(false); + Log.Info(removed ? "token Telegram rimosso: Telegram spento" : "nessun token Telegram da rimuovere"); + return new SecretActionResult(true, removed ? "token rimosso: Telegram spento" : "nessun token salvato da rimuovere"); + } + + public async Task TelegramTestAsync(CancellationToken ct) + { + if (_hooks.SendTelegramTest is not { } send) + { + return new SecretActionResult(false, "Telegram non è disponibile in questo processo", HttpStatus: 409); + } + + (bool ok, string message) = await send(ct).ConfigureAwait(false); + return new SecretActionResult(ok, message, HttpStatus: ok ? 200 : 400); + } + + /// Opens a store locked by a password change with the previous password; the secrets are encrypted again with the current one. + public async Task UnlockAsync(string? previous, CancellationToken ct) + { + await _lock.WaitAsync(ct).ConfigureAwait(false); + bool ok; + string message; + try + { + ok = Secrets.Unlock(previous ?? string.Empty, out message); + if (ok) + { + Interlocked.Increment(ref _version); + _hooks.InvalidateHistory?.Invoke(); + } + } + finally + { + _lock.Release(); + } + + if (ok) + { + await ReconfigureNotifierAsync().ConfigureAwait(false); + Log.Info($"segreti: {message}"); + } + + return new SecretActionResult(ok, message, HttpStatus: ok ? 200 : 400); + } + + /// Starts again with an empty store; the old file stays as a dated .bak. + public async Task ResetSecretsAsync(CancellationToken ct) + { + await _lock.WaitAsync(ct).ConfigureAwait(false); + string? backup; + try + { + backup = Secrets.Reset(); + Interlocked.Increment(ref _version); + _hooks.InvalidateHistory?.Invoke(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return new SecretActionResult(false, $"deposito non azzerato: {ex.Message}", HttpStatus: 500); + } + finally + { + _lock.Release(); + } + + await ReconfigureNotifierAsync().ConfigureAwait(false); + string message = backup is null ? "deposito dei segreti vuoto: reinserisci chiavi e token" : $"deposito dei segreti ricominciato vuoto (il precedente è in {Path.GetFileName(backup)}): reinserisci chiavi e token"; + Log.Warn(message); + return new SecretActionResult(true, message) { Detail = backup ?? string.Empty }; + } + + /// The factory encelado.json (engine stopped): the previous file stays beside it with the date. + public async Task RestoreAsync(CancellationToken ct) + { + await _lock.WaitAsync(ct).ConfigureAwait(false); + string? backup; + try + { + if (Supervisor.IsRunning) + { + return new SecretActionResult(false, "ferma il motore prima di ripristinare la configurazione", HttpStatus: 409); + } + + if (Config.Run.Mode.IsLive() && AccountActivity.FromDisk(Config.Run.DataPath).Busy) + { + return new SecretActionResult(false, "il ripristino riporta il conto a Demo, ma sul conto reale ci sono basket o ordini aperti: chiudili prima", HttpStatus: 409); + } + + backup = ConfigDefaults.Restore(ConfigPath); + await RefreshMemoryAsync(["notifications.telegram.enabled"], accountChange: true).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return new SecretActionResult(false, ex.Message, HttpStatus: 500); + } + finally + { + _lock.Release(); + } + + string message = backup is null ? "configurazione ripristinata ai valori di fabbrica" : $"configurazione ripristinata ai valori di fabbrica; la precedente è in {Path.GetFileName(backup)}"; + Log.Info(message); + return new SecretActionResult(true, message) { Detail = backup ?? string.Empty }; + } + + // ----------------------------------------------------------------------- + // Helpers + // ----------------------------------------------------------------------- + + private BotConfig ConfigFromFileOrMemory() + { + try + { + return ConfigLoader.Load(ConfigPath, out _); + } + catch (Exception ex) when (ex is IOException or JsonException or InvalidOperationException or UnauthorizedAccessException) + { + return Config; + } + } + + private static bool? ParseAccount(string? account) => (account ?? string.Empty).Trim().ToLowerInvariant() switch + { + "demo" => true, + "live" or "real" or "reale" => false, + _ => null, + }; + + private static SettingsResult Failure(string message) => + new(false, message, [], SettingsResult.RestartNone, new Dictionary { ["*"] = message }); + + private static SettingsResult Refused(string message) => + new(false, message, [], SettingsResult.RestartRefused, new Dictionary()); + + /// The default proof of a pair of keys: the profile, then the balance of that very account. + public static async Task VerifyEtoroKeysAsync(EtoroOptions options, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(options); + using CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(ct); + cts.CancelAfter(TimeSpan.FromSeconds(25)); + await using EtoroBroker broker = new(options); + string user = await broker.VerifyAsync(cts.Token).ConfigureAwait(false); + AccountSnapshot account = await broker.GetAccountAsync(cts.Token).ConfigureAwait(false); + return string.Create(CultureInfo.InvariantCulture, $"utente {user}, equity {account.Equity:N2} {account.Currency}"); + } + + private Task VerifyTelegramTokenAsync(string token, CancellationToken ct) => + TelegramNotifier.GetMeAsync(token, Config.Notifications.Telegram.BaseUrl, null, ct); +} diff --git a/Encelado/src/Encelado.Engine/Settings/SettingsService.cs b/Encelado/src/Encelado.Engine/Settings/SettingsService.cs index bbd5179..e6c0dda 100644 --- a/Encelado/src/Encelado.Engine/Settings/SettingsService.cs +++ b/Encelado/src/Encelado.Engine/Settings/SettingsService.cs @@ -1,106 +1,67 @@ using System.Globalization; -using System.Text; using System.Text.Json; using System.Text.Json.Nodes; +using Encelado.Core.Baskets; using Encelado.Engine.Configuration; namespace Encelado.Engine.Settings; +/// A batch of edits checked field by field: what changes in which file, and what was refused. +public sealed class SettingsPlan +{ + /// The fields whose value changes, by API path. + public Dictionary Changed { get; } = new(StringComparer.OrdinalIgnoreCase); + + public Dictionary ConfigChanges { get; } = new(StringComparer.Ordinal); + + public List ConfigDeletions { get; } = []; + + public Dictionary StrategyChanges { get; } = new(StringComparer.Ordinal); + + public List StrategyDeletions { get; } = []; + + /// Path → why the value was refused. + public Dictionary Errors { get; } = new(StringComparer.OrdinalIgnoreCase); + + public bool TouchesConfig => ConfigChanges.Count > 0 || ConfigDeletions.Count > 0; + + public bool TouchesStrategy => StrategyChanges.Count > 0 || StrategyDeletions.Count > 0; +} + /// -/// The settings page as an API: the catalogue as JSON, and a batch of changes applied -/// to encelado.json only when every field validates on its own and the whole -/// file validates as a configuration. Half a settings page never gets written. +/// The settings page as an API: the catalogue as JSON, and a batch of changes applied to +/// encelado.json and strategy.json only when every field validates on its own +/// and each whole file validates as a configuration. Half a settings page never gets +/// written. The runtime part — what a saved value does to the running bot — is +/// . /// public static class SettingsService { - /// The groups and fields of the catalogue, with the current values. - public static string Describe(BotConfig config, string configPath, string keysDescription, string strategyPath) + /// Checks a batch against the catalogue built from the files as they are now. + public static SettingsPlan Plan(IReadOnlyList groups, IReadOnlyDictionary edits) { - ArgumentNullException.ThrowIfNull(config); - using MemoryStream ms = new(); - using (Utf8JsonWriter w = new(ms)) - { - w.WriteStartObject(); - w.WriteString("configPath", configPath); - w.WriteString("strategyPath", strategyPath); - w.WriteString("keys", keysDescription); - w.WriteStartArray("groups"); - foreach (SettingGroup g in SettingsCatalogue.Build(config)) - { - w.WriteStartObject(); - w.WriteString("title", g.Title); - w.WriteString("description", g.Description); - w.WriteStartArray("fields"); - foreach (SettingField f in g.Fields) - { - w.WriteStartObject(); - w.WriteString("path", f.Path); - w.WriteString("label", f.Label); - w.WriteString("value", f.Value); - w.WriteString("kind", f.Kind.ToString().ToLowerInvariant()); - w.WriteString("suffix", f.Suffix); - w.WriteString("tooltip", f.FullTooltip); - w.WriteBoolean("readOnly", f.IsReadOnly); - w.WriteBoolean("allowEmpty", f.AllowEmpty); - w.WriteString("error", f.Error ?? string.Empty); - if (double.IsFinite(f.Minimum)) { w.WriteNumber("minimum", f.Minimum); } - if (double.IsFinite(f.Maximum)) { w.WriteNumber("maximum", f.Maximum); } - w.WriteStartArray("options"); - foreach (string o in f.Options) - { - w.WriteStringValue(o); - } - - w.WriteEndArray(); - w.WriteEndObject(); - } - - w.WriteEndArray(); - w.WriteEndObject(); - } - - w.WriteEndArray(); - w.WriteEndObject(); - } - - return Encoding.UTF8.GetString(ms.ToArray()); - } - - /// - /// Applies a batch of path → value edits: field validation first, then the - /// whole configuration on a throwaway copy, then one atomic write. Returns what - /// happened in words the page can show. - /// - public static (bool Ok, string Message, int Applied) Apply(BotConfig config, string configPath, IReadOnlyDictionary edits) - { - ArgumentNullException.ThrowIfNull(config); + ArgumentNullException.ThrowIfNull(groups); ArgumentNullException.ThrowIfNull(edits); - if (edits.Count == 0) - { - return (false, "nessuna modifica", 0); - } - - Dictionary fields = SettingsCatalogue.Build(config).SelectMany(static g => g.Fields).ToDictionary(static f => f.Path, StringComparer.OrdinalIgnoreCase); - Dictionary changes = []; - List problems = []; + SettingsPlan plan = new(); + Dictionary fields = SettingsCatalogue.Index(groups); foreach ((string path, string value) in edits) { - if (!fields.TryGetValue(path, out SettingField? field)) + if (!fields.TryGetValue(path.Trim(), out SettingField? field)) { - problems.Add($"{path}: campo sconosciuto"); + plan.Errors[path] = "campo sconosciuto"; continue; } if (field.IsReadOnly) { - problems.Add($"{path}: non modificabile"); + plan.Errors[field.Path] = field.ReadOnlyReason is { } why ? $"non modificabile: {why}" : "non modificabile"; continue; } field.Value = value ?? string.Empty; if (field.HasError) { - problems.Add($"{field.Label}: {field.Error}"); + plan.Errors[field.Path] = field.Error!; continue; } @@ -109,39 +70,71 @@ public static class SettingsService continue; } - try + plan.Changed[field.Path] = field; + bool strategy = field.Target == SettingTarget.Strategy; + if (field.IsDeletion) { - changes[field.Path] = field.ToJson(); + (strategy ? plan.StrategyDeletions : plan.ConfigDeletions).Add(field.FilePath); } - catch (Exception ex) when (ex is FormatException or OverflowException or ArgumentException) + else { - problems.Add($"{field.Label}: {ex.Message}"); + (strategy ? plan.StrategyChanges : plan.ConfigChanges)[field.FilePath] = field.ToJson(); } } - if (problems.Count > 0) - { - return (false, string.Join("; ", problems), 0); - } + return plan; + } - if (changes.Count == 0) - { - return (true, "nessun valore diverso da quello salvato", 0); - } - - // The whole validator on a copy, not a subset: single values can each be - // reasonable while the combination is not, and finding that out at the next start - // is the worst moment. - string temporary = Path.Combine(Path.GetTempPath(), $"encelado-check-{Guid.NewGuid():N}.json"); + /// + /// The whole validator of each touched file on a throwaway copy, not a subset: single + /// values can each be reasonable while the combination is not, and finding that out at + /// the next start is the worst moment. Returns the configuration as it will be, or the + /// reason it would not be valid. + /// + public static (BotConfig? Config, BasketStrategyConfig? Strategy, string? Error) Validate(string configPath, string strategyPath, SettingsPlan plan) + { + ArgumentNullException.ThrowIfNull(plan); + BotConfig? config = null; + BasketStrategyConfig? strategy = null; try { - File.Copy(configPath, temporary, overwrite: true); - ConfigWriter.Apply(temporary, changes); - ConfigLoader.Load(temporary, out _).Validate(); + config = OnCopy(configPath, plan.ConfigChanges, plan.ConfigDeletions, static p => ConfigLoader.Load(p, out _).Validate(), plan.TouchesConfig); } catch (Exception ex) when (ex is InvalidOperationException or IOException or ArgumentException or UnauthorizedAccessException or JsonException) { - return (false, $"la combinazione di valori non è valida: {ex.Message}", 0); + return (null, null, $"la combinazione di valori non è valida: {ex.Message}"); + } + + try + { + strategy = OnCopy(strategyPath, plan.StrategyChanges, plan.StrategyDeletions, static p => + { + BasketStrategyConfig s = BasketStrategyConfig.Load(p, out _); + s.Validate(); + return s; + }, plan.TouchesStrategy); + } + catch (Exception ex) when (ex is InvalidOperationException or IOException or ArgumentException or UnauthorizedAccessException or JsonException) + { + return (config, null, $"la strategia non sarebbe valida: {ex.Message}"); + } + + return (config, strategy, null); + } + + private static T OnCopy(string path, Dictionary changes, List deletions, Func load, bool touched) + { + if (!touched) + { + return load(path); + } + + string temporary = Path.Combine(Path.GetTempPath(), $"encelado-check-{Guid.NewGuid():N}.json"); + try + { + File.Copy(path, temporary, overwrite: true); + ConfigWriter.Apply(temporary, changes, deletions); + return load(temporary); } finally { @@ -154,17 +147,163 @@ public static class SettingsService // A leftover in the temp folder is not worth failing the save over. } } - - try - { - ConfigWriter.Apply(configPath, changes); - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or FileNotFoundException or ArgumentException) - { - return (false, $"salvataggio non riuscito: {ex.Message}", 0); - } - - return (true, string.Create(CultureInfo.InvariantCulture, $"{changes.Count} valore/i salvati in {configPath}; i valori del motore hanno effetto al prossimo avvio, quelli dell'interfaccia subito"), changes.Count); } + /// + /// Writes the batch: the strategy first, then the configuration (with the keys of 5.0 that + /// no longer exist removed on the way). Each file is written atomically; a failure on + /// the second leaves the first written and says so. + /// + public static void Write(string configPath, string strategyPath, SettingsPlan plan) + { + ArgumentNullException.ThrowIfNull(plan); + if (plan.TouchesStrategy) + { + ConfigWriter.Apply(strategyPath, WithDocumentation(strategyPath, BasketStrategyConfig.DefaultJson, plan.StrategyChanges), plan.StrategyDeletions); + } + + if (plan.TouchesConfig) + { + List deletions = [.. plan.ConfigDeletions, .. ConfigLoader.ObsoleteKeys.Where(k => ConfigWriter.Contains(configPath, k))]; + try + { + ConfigWriter.Apply(configPath, WithDocumentation(configPath, ConfigDefaults.Json, plan.ConfigChanges), deletions); + } + catch (Exception ex) when (plan.TouchesStrategy && ex is IOException or UnauthorizedAccessException or InvalidOperationException) + { + throw new IOException($"strategy.json salvato, encelado.json NO: {ex.Message}", ex); + } + } + } + + /// The edits plus the documentation lines of the file that an older version wrote (). + public static Dictionary WithDocumentation(string path, string factoryJson, IReadOnlyDictionary changes) + { + ArgumentNullException.ThrowIfNull(changes); + Dictionary all = ConfigWriter.DocumentationUpdates(path, factoryJson); + foreach ((string key, JsonNode? value) in changes) + { + all[key] = value; + } + + return all; + } + + // ----------------------------------------------------------------------- + // JSON + // ----------------------------------------------------------------------- + + /// The groups of the catalogue in the shape of GET /api/settings (docs/API.md). + public static void WriteGroups(Utf8JsonWriter w, IReadOnlyList groups) + { + ArgumentNullException.ThrowIfNull(w); + ArgumentNullException.ThrowIfNull(groups); + w.WriteStartArray("groups"); + foreach (SettingGroup g in groups) + { + w.WriteStartObject(); + w.WriteString("key", g.Key); + w.WriteString("title", g.Title); + w.WriteString("description", g.Description); + w.WriteString("target", g.Target == SettingTarget.Strategy ? "strategy" : "config"); + w.WriteBoolean("advanced", g.Advanced); + w.WriteStartArray("fields"); + foreach (SettingField f in g.Fields) + { + w.WriteStartObject(); + w.WriteString("path", f.Path); + w.WriteString("label", f.Label); + w.WriteString("kind", f.KindName); + w.WriteString("value", f.Value); + w.WriteStartArray("options"); + foreach (string o in f.Options) + { + w.WriteStringValue(o); + } + + w.WriteEndArray(); + w.WriteString("suffix", f.Suffix); + w.WriteString("tooltip", f.FullTooltip); + w.WriteBoolean("readOnly", f.IsReadOnly); + w.WriteString("error", f.Error ?? string.Empty); + w.WriteString("scope", f.ScopeName); + Bound(w, "min", f.Minimum); + Bound(w, "max", f.Maximum); + w.WriteBoolean("allowEmpty", f.AllowEmpty); + w.WriteEndObject(); + } + + w.WriteEndArray(); + w.WriteEndObject(); + } + + w.WriteEndArray(); + } + + /// The secrets object of GET /api/settings (and of /api/system). + public static void WriteSecrets(Utf8JsonWriter w, string name, SecretsSummary s) + { + ArgumentNullException.ThrowIfNull(w); + ArgumentNullException.ThrowIfNull(s); + w.WriteStartObject(name); + w.WriteString("state", s.State); + w.WriteStartObject("etoro"); + WriteSecret(w, "demo", s.Demo); + WriteSecret(w, "live", s.Live); + w.WriteEndObject(); + WriteSecret(w, "telegram", s.Telegram); + w.WriteString("passwordSource", s.PasswordSource); + w.WriteStartArray("ignoredEnv"); + foreach (string v in s.IgnoredEnv) + { + w.WriteStringValue(v); + } + + w.WriteEndArray(); + w.WriteString("importNote", s.ImportNote); + w.WriteString("problem", s.Problem); + w.WriteEndObject(); + } + + public static void WriteSecret(Utf8JsonWriter w, string name, SecretInfo info) + { + ArgumentNullException.ThrowIfNull(w); + ArgumentNullException.ThrowIfNull(info); + w.WriteStartObject(name); + w.WriteBoolean("present", info.Present); + w.WriteString("masked", info.Masked); + if (info.SavedUtc is { } t) + { + w.WriteString("savedUtc", t.ToString("O", CultureInfo.InvariantCulture)); + } + else + { + w.WriteNull("savedUtc"); + } + + w.WriteEndObject(); + } + + private static void Bound(Utf8JsonWriter w, string name, double v) + { + if (double.IsFinite(v)) + { + w.WriteNumber(name, v); + } + else + { + w.WriteNull(name); + } + } } + +/// The secrets as the settings page and the diagnostics show them: never a whole secret. +public sealed record SecretsSummary( + string State, + SecretInfo Demo, + SecretInfo Live, + SecretInfo Telegram, + string PasswordSource, + IReadOnlyList IgnoredEnv, + string ImportNote, + string Problem); diff --git a/Encelado/src/Encelado.Engine/Settings/StrategyCache.cs b/Encelado/src/Encelado.Engine/Settings/StrategyCache.cs new file mode 100644 index 0000000..70ebd08 --- /dev/null +++ b/Encelado/src/Encelado.Engine/Settings/StrategyCache.cs @@ -0,0 +1,83 @@ +using System.Text.Json; +using Encelado.Core.Baskets; + +namespace Encelado.Engine.Settings; + +/// +/// strategy.json as the file says now, parsed again only when the file changed +/// (its time and size). The idle snapshot, the settings page and the diagnostics read it +/// many times a second between them; parsing it for each was a waste (5.1). The instance +/// handed out is shared: callers read it and never change it — the engine loads its own. +/// A missing or unreadable file gives the factory strategy, and says why. +/// +public sealed class StrategyCache(string path) +{ + private readonly Lock _gate = new(); + private (DateTime Stamp, long Length, BasketStrategyConfig Value)? _cached; + private string _problem = string.Empty; + + public string Path => path; + + /// Why the file could not be read at the last attempt, or empty. + public string Problem + { + get + { + lock (_gate) + { + return _problem; + } + } + } + + public BasketStrategyConfig Current() + { + (DateTime stamp, long length) = Stamp(); + lock (_gate) + { + if (_cached is { } c && c.Stamp == stamp && c.Length == length) + { + return c.Value; + } + + BasketStrategyConfig value; + try + { + value = length >= 0 + ? BasketStrategyConfig.Load(path, out _) + : BasketStrategyConfig.ParseText(BasketStrategyConfig.DefaultJson, out _); + _problem = length >= 0 ? string.Empty : $"{path} non esiste: valori di fabbrica"; + } + catch (Exception ex) when (ex is IOException or InvalidOperationException or JsonException or UnauthorizedAccessException) + { + _problem = $"strategy.json non leggibile: {ex.Message}"; + value = _cached?.Value ?? BasketStrategyConfig.ParseText(BasketStrategyConfig.DefaultJson, out _); + } + + _cached = (stamp, length, value); + return value; + } + } + + /// Forgets the cached copy: the next read parses the file again (after a save). + public void Invalidate() + { + lock (_gate) + { + _cached = null; + } + } + + private (DateTime Stamp, long Length) Stamp() + { + try + { + FileInfo fi = new(path); + return fi.Exists ? (fi.LastWriteTimeUtc, fi.Length) : (DateTime.MinValue, -1); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) + { + return (DateTime.MinValue, -1); + } + } +} diff --git a/Encelado/src/Encelado.Etoro/EtoroHttp.cs b/Encelado/src/Encelado.Etoro/EtoroHttp.cs index 5ec4223..3ecfa6c 100644 --- a/Encelado/src/Encelado.Etoro/EtoroHttp.cs +++ b/Encelado/src/Encelado.Etoro/EtoroHttp.cs @@ -57,7 +57,11 @@ public sealed class EtoroHttp : IDisposable _client = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: true); _client.BaseAddress = new Uri(options.BaseUrl.TrimEnd('/') + "/"); - _client.Timeout = TimeSpan.FromSeconds(options.RequestTimeoutSeconds); + + // The timeout is applied per request from the options (read at every call), so a + // new value saved in the settings reaches a running engine without a restart; + // HttpClient.Timeout cannot change after the first request. + _client.Timeout = Timeout.InfiniteTimeSpan; _client.DefaultRequestHeaders.UserAgent.ParseAdd(options.UserAgent); _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); if (options.HasKeys) @@ -113,11 +117,13 @@ public sealed class EtoroHttp : IDisposable } HttpResponseMessage response; + using CancellationTokenSource timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(TimeSpan.FromSeconds(Math.Clamp(_options.RequestTimeoutSeconds, 3, 120))); try { - response = await _client.SendAsync(request, HttpCompletionOption.ResponseContentRead, ct).ConfigureAwait(false); + response = await _client.SendAsync(request, HttpCompletionOption.ResponseContentRead, timeout.Token).ConfigureAwait(false); } - catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException && !ct.IsCancellationRequested) + catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException && !ct.IsCancellationRequested) { lastError = ex; OnLog?.Invoke($"eToro {method} {path}: tentativo {attempt + 1} fallito", ex); diff --git a/Encelado/src/Encelado.Etoro/EtoroOptions.cs b/Encelado/src/Encelado.Etoro/EtoroOptions.cs index d616c5e..fb9f366 100644 --- a/Encelado/src/Encelado.Etoro/EtoroOptions.cs +++ b/Encelado/src/Encelado.Etoro/EtoroOptions.cs @@ -1,15 +1,19 @@ namespace Encelado.Etoro; /// -/// How to reach eToro Public API on behalf of one account. The keys never come from the -/// committed configuration: they arrive from the encrypted store, the environment or the -/// login window, and are filled in at runtime. +/// How to reach eToro Public API on behalf of one account. The keys never come from a +/// configuration file: they live in the encrypted secret store and are copied into a +/// private instance of these options by whoever talks to the venue (the engine, the +/// history page, the key check), never into the shared configuration. /// public sealed class EtoroOptions { public const string DefaultBaseUrl = "https://public-api.etoro.com"; - /// demo or real. Demo and real use different keys and different routes. + /// + /// demo or real. Demo and real use different keys and different routes. + /// Derived from the execution mode since 5.1 (Demo → demo, Live → real), never set on its own. + /// public string Environment { get; set; } = "demo"; /// The application key (x-api-key). diff --git a/Encelado/src/Encelado.Server/Program.cs b/Encelado/src/Encelado.Server/Program.cs index 44a1897..caa0bf9 100644 --- a/Encelado/src/Encelado.Server/Program.cs +++ b/Encelado/src/Encelado.Server/Program.cs @@ -14,16 +14,20 @@ using Microsoft.AspNetCore.Builder; namespace Encelado.Server; /// -/// The process: loads the configuration, starts the log, the notifier, the supervisor -/// and the web host, starts the engine (unless told otherwise), then waits for SIGTERM, -/// Ctrl+C, stop on the console or the minutes to run out. One instance per data -/// folder, enforced by the engine's lock. +/// The process: resolves the interface password, loads the configuration, opens the +/// secret store, imports once what a 5.0 container kept in its variables, starts the log, +/// the notifier hub, the supervisor, the settings runtime and the web host, starts the +/// engine (unless told otherwise), then waits for SIGTERM, Ctrl+C, stop on the +/// console or the minutes to run out. One instance per data folder, enforced by the +/// engine's lock. /// /// Arguments: --health (probe the running server and exit 0/1), --sample /// (serve a sample snapshot, no market), --no-autostart, --bonifica, -/// --minutes N, --confirm-live "CONFERMO LIVE", --port N. -/// Environment: ENCELADO_WEB_PORT, ENCELADO_WEB_TOKEN, -/// ENCELADO_CONFIRM_LIVE, ENCELADO_AUTOSTART, plus those of the configuration loader. +/// --minutes N, --port N. Environment: ENCELADO_PASSWORD (the only +/// setting a container needs; ENCELADO_WEB_TOKEN is its deprecated alias) and the +/// image's own ENCELADO_WEB_PORT, ENCELADO_CONFIG_DIR, ENCELADO_DATA_DIR. +/// Everything else is set from the interface (5.1); Live never starts without a person +/// typing the phrase there. /// /// public static class Program @@ -35,6 +39,8 @@ public static class Program return await HealthAsync().ConfigureAwait(false); } + InterfacePassword password = InterfacePassword.Resolve(Environment.GetEnvironmentVariable); + BotConfig config; try { @@ -65,27 +71,82 @@ public static class Program Log.Warn(seeded); } + foreach (string warning in password.Warnings) + { + Log.Warn($"password dell'interfaccia: {warning}"); + } + bool sample = Has(args, "--sample"); bool bonifica = Has(args, "--bonifica"); - bool autostart = !Has(args, "--no-autostart") && Environment.GetEnvironmentVariable("ENCELADO_AUTOSTART") is not ("0" or "false") && !sample; int minutes = IntArg(args, "--minutes"); - string? liveConfirmation = Arg(args, "--confirm-live") ?? Environment.GetEnvironmentVariable("ENCELADO_CONFIRM_LIVE"); int port = IntArg(args, "--port") is > 0 and var p ? p : WebHost.Port; - string token = WebHost.Token; - INotifier notifier = Notifications.Create(config); - await using BotSupervisor supervisor = new(config, (c, confirmed) => new BasketEngine(c, confirmed, null, notifier) { OrphanPolicy = bonifica ? OrphanPolicy.Report : OrphanPolicy.Close }, notifier); - if (notifier is TelegramNotifier telegram) + // The secrets: encrypted with the interface password, or with a local key without one. + string configDirectory = Path.GetDirectoryName(Path.GetFullPath(AppPaths.ConfigPath)) ?? AppPaths.ConfigDirectory; + SecretStore secrets = new(configDirectory, password.Value); + if (secrets.OpenNote is { } opened) { - TelegramCommands commands = new(supervisor, () => notifier.Status); - telegram.CommandHandler = commands.HandleAsync; - telegram.StartCommands(); + Log.Info($"segreti: {opened}"); + } + + switch (secrets.State) + { + case SecretStoreState.Locked: + Log.Warn($"segreti BLOCCATI: {secrets.Problem}. Sbloccali con la password precedente o ricomincia da Impostazioni ▸ Conto; il motore non può partire finché restano bloccati."); + break; + case SecretStoreState.LocalKey: + Log.Warn("segreti cifrati con una chiave locale (secrets.key): senza password dell'interfaccia il server ascolta solo su localhost"); + break; + } + + // What a 5.0 container kept in its variables moves once to the store and the file. + ImportOutcome import = sample ? ImportOutcome.Nothing : EnvironmentImport.Run(AppPaths.ConfigPath, secrets, Environment.GetEnvironmentVariable, DateTime.UtcNow); + if (import.Ran) + { + Log.Info(import.Imported.Count > 0 ? $"importazione una tantum dalla 5.0: {string.Join(", ", import.Imported)}" : "importazione una tantum dalla 5.0: niente da importare"); + foreach (string note in import.Notes) + { + Log.Warn($"importazione: {note}"); + } + } + + if (import.ConfigChanged) + { + config.CopyFrom(ConfigLoader.Load(AppPaths.ConfigPath, out _)); + Log.Reconfigure(config.Logging); + } + + foreach (string variable in import.Ignored) + { + Log.Warn($"variabile d'ambiente {variable} ignorata: dalla 5.1 si configura tutto dall'interfaccia, puoi toglierla dal container"); } LogBuffer buffer = new(config.Logging.BufferedLines); + await using NotifierHub hub = new(config.Notifications.Telegram, () => secrets.TelegramToken, static m => Log.Info(m)); + await using BotSupervisor supervisor = new(config, (c, confirmed) => new BasketEngine(c, secrets.Etoro(demo: !c.Run.Mode.IsLive()), confirmed, null, hub) { OrphanPolicy = bonifica ? OrphanPolicy.Report : OrphanPolicy.Close }, hub); + hub.CommandHandler = new TelegramCommands(supervisor, () => hub.Status).HandleAsync; + await hub.ReconfigureAsync().ConfigureAwait(false); + supervisor.EventLogged += buffer.Add; supervisor.AttachLogSink(); - await using HistoryService history = new(config); + await using HistoryService history = new(config, demo => secrets.Etoro(demo)); + + SettingsRuntime settings = new(config, AppPaths.ConfigPath, secrets, supervisor, new SettingsHooks + { + ReconfigureProcess = c => + { + Log.Reconfigure(c.Logging); + buffer.Resize(c.Logging.BufferedLines); + UiClock.Zone = c.Ui.ResolveTimeZone(out _); + }, + ReconfigureNotifier = hub.ReconfigureAsync, + InvalidateHistory = history.Invalidate, + SendTelegramTest = hub.SendTestAsync, + }) + { + Import = import, + PasswordSource = password.Source, + }; WebContext ctx = new() { @@ -94,12 +155,15 @@ public static class Program Log = buffer, History = history, ConfigPath = AppPaths.ConfigPath, + Settings = settings, Sample = sample, - Start = confirm => StartAsync(supervisor, config, confirm ?? liveConfirmation), + Start = confirm => sample + ? Task.FromResult(new CommandResult(false, "modalità dimostrativa (--sample): il motore non parte")) + : settings.StartEngineAsync(confirm), Learn = () => LearnAsync(config), }; - WebApplication web = WebHost.Build(ctx, port, token, listenAll: token.Length > 0); + WebApplication web = WebHost.Build(ctx, port, password.Value, listenAll: password.IsSet); try { await web.StartAsync().ConfigureAwait(false); @@ -110,9 +174,10 @@ public static class Program return 6; } - Log.Info(token.Length > 0 - ? $"interfaccia web su http://localhost:{port}/ (in ascolto su tutte le interfacce, token da {WebHost.TokenVariable})" - : $"interfaccia web su http://localhost:{port}/ (solo localhost: senza {WebHost.TokenVariable} il server non ascolta fuori dal computer)"); + // "in ascolto su " is what VS Code's serverReadyAction waits for to open the browser. + Log.Info(password.IsSet + ? $"interfaccia web in ascolto su http://localhost:{port}/ (anche dalla rete, password da {password.Source})" + : $"interfaccia web in ascolto su http://localhost:{port}/ (solo localhost: senza {InterfacePassword.Variable} il server non ascolta fuori dal computer e non chiede la password)"); using CancellationTokenSource stopping = new(); Console.CancelKeyPress += (_, e) => @@ -124,9 +189,9 @@ public static class Program // docker stop sends SIGTERM to PID 1 (this process, via exec in the entrypoint). // Cancelling the runtime's default handling keeps the process alive until the // shutdown below has run: engine stopped, ledger closed, heartbeat with the note. - using PosixSignalRegistration sigterm = PosixSignalRegistration.Create(PosixSignal.SIGTERM, ctx => + using PosixSignalRegistration sigterm = PosixSignalRegistration.Create(PosixSignal.SIGTERM, signal => { - ctx.Cancel = true; + signal.Cancel = true; if (!stopping.IsCancellationRequested) { Log.Info("SIGTERM: arresto"); @@ -134,25 +199,35 @@ public static class Program } }); - if (sample) + switch (AutostartPolicy.Decide(Has(args, "--no-autostart"), sample, config)) { - Log.Warn("modalità dimostrativa (--sample): lo snapshot è finto, il motore non parte"); - } - else if (autostart) - { - CommandResult started = await StartAsync(supervisor, config, liveConfirmation).ConfigureAwait(false); - if (!started.Ok) + case AutostartDecision.Sample: + Log.Warn("modalità dimostrativa (--sample): lo snapshot è finto, il motore non parte"); + break; + case AutostartDecision.NoAutostartFlag: + Log.Info("motore non avviato (--no-autostart): premi AVVIA nell'interfaccia"); + break; + case AutostartDecision.Disabled: + Log.Info("motore non avviato (avvio automatico spento in Impostazioni ▸ Esecuzione): premi AVVIA nell'interfaccia"); + break; + case AutostartDecision.LiveWaits: + Log.Warn("modalità Live: il motore non parte da solo. I basket aperti hanno solo gli stop nativi finché non premi AVVIA e scrivi CONFERMO LIVE"); + hub.Notify(NotificationKind.Alert, "Live: motore fermo", "Il container è ripartito in modalità Live e il motore non parte da solo: i basket aperti hanno solo gli stop nativi. Apri l'interfaccia, premi AVVIA e scrivi CONFERMO LIVE."); + break; + default: { - Log.Error($"avvio del motore non riuscito: {started.Message}. Il server web resta attivo per correggere la configurazione.", null); + CommandResult started = await settings.StartEngineAsync(null).ConfigureAwait(false); + if (!started.Ok) + { + Log.Error($"avvio del motore non riuscito: {started.Message}. Il server web resta attivo per correggere la configurazione.", null); + } + else if (bonifica) + { + await HeadlessRunner.BonificaAsync(supervisor, stopping.Token).ConfigureAwait(false); + } + + break; } - else if (bonifica) - { - await HeadlessRunner.BonificaAsync(supervisor, stopping.Token).ConfigureAwait(false); - } - } - else - { - Log.Info("motore non avviato (--no-autostart o ENCELADO_AUTOSTART=0): premi AVVIA nell'interfaccia"); } if (minutes > 0) @@ -190,40 +265,11 @@ public static class Program // Shutting down anyway. } - if (notifier is IAsyncDisposable disposable) - { - await disposable.DisposeAsync().ConfigureAwait(false); - } - await Log.FlushAsync(TimeSpan.FromSeconds(5)).ConfigureAwait(false); await Log.ShutdownAsync().ConfigureAwait(false); return 0; } - /// Starts the engine after the gates: keys present, the live phrase when the mode is live. - private static async Task StartAsync(BotSupervisor supervisor, BotConfig config, string? liveConfirmation) - { - if (!KeyStores.Resolve(config, out string origin)) - { - return new CommandResult(false, $"{origin}: imposta ETORO_API_KEY e ETORO_USER_KEY nel container, oppure salva le chiavi da Impostazioni con {KeyStores.PassphraseVariable} nell'ambiente"); - } - - Log.Info($"chiavi eToro: {origin}"); - ExecutionMode mode = config.Run.Mode; - if (mode.IsLive()) - { - if (!LiveConfirmation.IsConfirmed(liveConfirmation)) - { - return new CommandResult(false, $"la modalità Live richiede la frase {LiveConfirmation.Phrase} (--confirm-live, ENCELADO_CONFIRM_LIVE o la finestra di conferma)"); - } - - Log.Warn("avvio in Live sul conto REALE confermato"); - } - - supervisor.StartConfirmed = true; - return await supervisor.StartAsync().ConfigureAwait(false); - } - /// The learning cycle on demand: reads the ledger and writes the knowledge base, without touching the running engine. private static Task LearnAsync(BotConfig config) { diff --git a/Encelado/src/Encelado.Server/Web/LogBuffer.cs b/Encelado/src/Encelado.Server/Web/LogBuffer.cs index 94d46b0..f05a0da 100644 --- a/Encelado/src/Encelado.Server/Web/LogBuffer.cs +++ b/Encelado/src/Encelado.Server/Web/LogBuffer.cs @@ -10,9 +10,46 @@ public sealed class LogBuffer(int capacity) { private readonly Lock _gate = new(); private readonly Queue<(long Seq, EventRow Row)> _rows = new(); - private readonly int _capacity = Math.Max(100, capacity); + private int _capacity = Math.Max(100, capacity); private long _seq; + /// How many lines the window keeps now. + public int Capacity + { + get + { + lock (_gate) + { + return _capacity; + } + } + } + + /// How many lines it holds now. + public int Count + { + get + { + lock (_gate) + { + return _rows.Count; + } + } + } + + /// A new size from the settings (logging.bufferedLines), applied at once: a smaller window drops the oldest lines. + public void Resize(int capacity) + { + lock (_gate) + { + _capacity = Math.Max(100, capacity); + while (_rows.Count > _capacity) + { + _rows.Dequeue(); + } + } + } + public void Add(EventRow row) { ArgumentNullException.ThrowIfNull(row); diff --git a/Encelado/src/Encelado.Server/Web/SettingsApi.cs b/Encelado/src/Encelado.Server/Web/SettingsApi.cs new file mode 100644 index 0000000..6c3c9b7 --- /dev/null +++ b/Encelado/src/Encelado.Server/Web/SettingsApi.cs @@ -0,0 +1,162 @@ +using System.Text; +using System.Text.Json; +using Encelado.Engine.Settings; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; + +namespace Encelado.Server.Web; + +/// +/// The routes of Impostazioni (docs/API.md, "Impostazioni" and "Segreti"): the catalogue, +/// the batch of edits applied by the running bot, the secrets of both eToro accounts and of +/// Telegram, the secret store's unlock and reset, the restore of the factory file. Every +/// decision is 's; this is the HTTP skin around it. +/// +internal static class SettingsApi +{ + public static void Map(WebApplication app, WebContext ctx) + { + app.MapGet("/api/settings", async http => await WriteAsync(http, 200, ctx.Settings.Describe()).ConfigureAwait(false)); + + app.MapPost("/api/settings", async http => + { + (Dictionary edits, string? confirm) = await ReadEditsAsync(http).ConfigureAwait(false); + SettingsResult r = await ctx.Settings.ApplyAsync(edits, confirm, http.RequestAborted).ConfigureAwait(false); + await WriteAsync(http, r.HttpStatus, Json.Object(w => + { + w.WriteBoolean("ok", r.Ok); + w.WriteString("message", r.Message); + w.WriteStartArray("results"); + foreach (SettingsPathResult p in r.Results) + { + w.WriteStartObject(); + w.WriteString("path", p.Path); + w.WriteString("applied", p.Applied); + w.WriteString("message", p.Message); + w.WriteEndObject(); + } + + w.WriteEndArray(); + w.WriteString("restart", r.Restart); + w.WriteBoolean("needsPhrase", r.Restart == SettingsResult.RestartNeedsPhrase); + w.WriteStartObject("errors"); + foreach ((string path, string error) in r.Errors) + { + w.WriteString(path, error); + } + + w.WriteEndObject(); + w.WriteNumber("version", ctx.Settings.Version); + })).ConfigureAwait(false); + }); + + app.MapPost("/api/settings/keys", async http => + { + Dictionary body = await Json.BodyAsync(http.Request.Body, http.RequestAborted).ConfigureAwait(false); + await SecretAsync(http, ctx, await ctx.Settings.SaveKeysAsync( + body.GetValueOrDefault("account"), body.GetValueOrDefault("apiKey"), body.GetValueOrDefault("userKey"), body.GetValueOrDefault("confirm"), http.RequestAborted).ConfigureAwait(false)).ConfigureAwait(false); + }); + + app.MapDelete("/api/settings/keys", async http => + await SecretAsync(http, ctx, await ctx.Settings.DeleteKeysAsync(http.Request.Query["account"], http.RequestAborted).ConfigureAwait(false)).ConfigureAwait(false)); + + app.MapPost("/api/settings/telegram-token", async http => + { + Dictionary body = await Json.BodyAsync(http.Request.Body, http.RequestAborted).ConfigureAwait(false); + await SecretAsync(http, ctx, await ctx.Settings.SaveTelegramTokenAsync(body.GetValueOrDefault("token"), http.RequestAborted).ConfigureAwait(false)).ConfigureAwait(false); + }); + + app.MapDelete("/api/settings/telegram-token", async http => + await SecretAsync(http, ctx, await ctx.Settings.DeleteTelegramTokenAsync(http.RequestAborted).ConfigureAwait(false)).ConfigureAwait(false)); + + app.MapPost("/api/settings/telegram-test", async http => + await SecretAsync(http, ctx, await ctx.Settings.TelegramTestAsync(http.RequestAborted).ConfigureAwait(false)).ConfigureAwait(false)); + + app.MapPost("/api/settings/secrets/unlock", async http => + { + Dictionary body = await Json.BodyAsync(http.Request.Body, http.RequestAborted).ConfigureAwait(false); + await SecretAsync(http, ctx, await ctx.Settings.UnlockAsync(body.GetValueOrDefault("previous"), http.RequestAborted).ConfigureAwait(false)).ConfigureAwait(false); + }); + + app.MapPost("/api/settings/secrets/reset", async http => + await SecretAsync(http, ctx, await ctx.Settings.ResetSecretsAsync(http.RequestAborted).ConfigureAwait(false)).ConfigureAwait(false)); + + app.MapPost("/api/settings/restore", async http => + await SecretAsync(http, ctx, await ctx.Settings.RestoreAsync(http.RequestAborted).ConfigureAwait(false)).ConfigureAwait(false)); + } + + private static Task SecretAsync(HttpContext http, WebContext ctx, SecretActionResult r) => + WriteAsync(http, r.HttpStatus, Json.Result(r.Ok, r.Message, w => + { + w.WriteString("restart", r.Restart); + w.WriteBoolean("needsPhrase", r.Restart == SettingsResult.RestartNeedsPhrase); + w.WriteString("detail", r.Detail); + w.WriteNumber("version", ctx.Settings.Version); + })); + + private static async Task WriteAsync(HttpContext http, int status, string json) + { + http.Response.StatusCode = status; + http.Response.ContentType = "application/json"; + http.Response.Headers.CacheControl = "no-store"; + await http.Response.WriteAsync(json, http.RequestAborted).ConfigureAwait(false); + } + + /// + /// { "edits": { "<path>": "<value>" }, "confirm"?: "CONFERMO LIVE" }, or the flat + /// object of 5.0 ({ "<path>": "<value>" }). Values may be strings, numbers, + /// booleans or arrays of strings (a list); everything becomes the string the catalogue parses. + /// + internal static async Task<(Dictionary Edits, string? Confirm)> ReadEditsAsync(HttpContext http) + { + Dictionary edits = new(StringComparer.OrdinalIgnoreCase); + string? confirm = null; + using StreamReader reader = new(http.Request.Body, Encoding.UTF8); + string text = await reader.ReadToEndAsync(http.RequestAborted).ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(text)) + { + return (edits, confirm); + } + + try + { + using JsonDocument doc = JsonDocument.Parse(text); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) + { + return (edits, confirm); + } + + if (root.TryGetProperty("confirm", out JsonElement c) && c.ValueKind == JsonValueKind.String) + { + confirm = c.GetString(); + } + + bool wrapped = root.TryGetProperty("edits", out JsonElement nested) && nested.ValueKind == JsonValueKind.Object; + JsonElement source = wrapped ? nested : root; + foreach (JsonProperty p in source.EnumerateObject()) + { + if (!wrapped && p.Name is "confirm" or "edits") + { + continue; + } + + edits[p.Name] = p.Value.ValueKind switch + { + JsonValueKind.String => p.Value.GetString() ?? string.Empty, + JsonValueKind.True => "true", + JsonValueKind.False => "false", + JsonValueKind.Null => string.Empty, + JsonValueKind.Array => string.Join(",", p.Value.EnumerateArray().Select(static e => e.ValueKind == JsonValueKind.String ? e.GetString() : e.GetRawText())), + _ => p.Value.GetRawText(), + }; + } + } + catch (JsonException) + { + // An unreadable body is an empty body: the answer says there is nothing to save. + } + + return (edits, confirm); + } +} diff --git a/Encelado/src/Encelado.Server/Web/WebHost.cs b/Encelado/src/Encelado.Server/Web/WebHost.cs index 22966e9..8718e8b 100644 --- a/Encelado/src/Encelado.Server/Web/WebHost.cs +++ b/Encelado/src/Encelado.Server/Web/WebHost.cs @@ -21,7 +21,7 @@ using Microsoft.Extensions.Logging; namespace Encelado.Server.Web; -/// What the web layer needs from the host: the supervisor, the log window, the history and the configuration. +/// What the web layer needs from the host: the supervisor, the log window, the history, the settings and the configuration. public sealed class WebContext { public required BotConfig Config { get; init; } @@ -34,12 +34,15 @@ public sealed class WebContext public required string ConfigPath { get; init; } + /// The settings and the secrets of the running bot (Impostazioni). + public required SettingsRuntime Settings { get; init; } + /// Serve the sample snapshot instead of the engine's (--sample): screenshots and UI work without a market. public bool Sample { get; init; } public DateTime StartedUtc { get; init; } = DateTime.UtcNow; - /// Called by the start endpoint; the host decides how the engine is built (live confirmation, bonifica). + /// Called by the start endpoint with the phrase typed in the dialog (Live needs it); the host decides how the engine is built. public required Func> Start { get; init; } /// The learning cycle on demand (Impostazioni → Ricerca). @@ -50,22 +53,51 @@ public sealed class WebContext /// /// The web host of §11 of the 5.0 plan: Kestrel, the embedded UI, a JSON API written -/// by hand, Server-Sent Events with one snapshot per second, commands over POST, and a -/// local token (ENCELADO_WEB_TOKEN) kept in an HttpOnly cookie. Without a token -/// the server listens on localhost only. +/// by hand, Server-Sent Events with one snapshot per second, commands over POST. +/// +/// 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 +/// Authorization: Bearer <password>. Every comparison is constant-time and a +/// wrong password costs a second. Without a password the server listens on localhost only +/// and asks for nothing (development). +/// /// public static class WebHost { - public const string TokenVariable = "ENCELADO_WEB_TOKEN"; public const string PortVariable = "ENCELADO_WEB_PORT"; - public const string CookieName = "encelado_token"; + public const string CookieName = "encelado_session"; public const int DefaultPort = 8080; + /// What a wrong password costs, so guessing it over the network is slow. + public static readonly TimeSpan FailedLoginDelay = TimeSpan.FromSeconds(1); + + /// The placeholder the login page may carry: a wrong password replaces it with the message. + public const string LoginErrorPlaceholder = ""; + public static int Port => int.TryParse(Environment.GetEnvironmentVariable(PortVariable), NumberStyles.Integer, CultureInfo.InvariantCulture, out int p) && p is > 0 and < 65536 ? p : DefaultPort; - public static string Token => Environment.GetEnvironmentVariable(TokenVariable)?.Trim() ?? string.Empty; + /// + /// The session cookie's value for a password: Base64Url(HMAC-SHA256(key = SHA-256("encelado/cookie/v1" ‖ password), "session")). + /// + public static string SessionValue(string password) + { + ArgumentNullException.ThrowIfNull(password); + byte[] prefix = "encelado/cookie/v1"u8.ToArray(); + byte[] secret = Encoding.UTF8.GetBytes(password); + byte[] material = new byte[prefix.Length + secret.Length]; + prefix.CopyTo(material, 0); + secret.CopyTo(material, prefix.Length); + byte[] key = SHA256.HashData(material); + byte[] mac = HMACSHA256.HashData(key, "session"u8); + CryptographicOperations.ZeroMemory(material); + CryptographicOperations.ZeroMemory(secret); + CryptographicOperations.ZeroMemory(key); + return System.Buffers.Text.Base64Url.EncodeToString(mac); + } - public static WebApplication Build(WebContext ctx, int port, string token, bool listenAll) + public static WebApplication Build(WebContext ctx, int port, string password, bool listenAll) { ArgumentNullException.ThrowIfNull(ctx); WebApplicationBuilder builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions { ApplicationName = "Encelado" }); @@ -90,9 +122,10 @@ public static class WebHost }); WebApplication app = builder.Build(); - app.Use(Auth(token)); - MapStatic(app, token); + app.Use(Auth(password)); + MapStatic(app, password); MapApi(app, ctx); + SettingsApi.Map(app, ctx); return app; } @@ -100,45 +133,56 @@ public static class WebHost // Authentication // ----------------------------------------------------------------------- - private static Func Auth(string token) => async (http, next) => + /// The paths open without a session: the login itself, the container's probe and the files the login page needs. + internal static bool IsPublic(string path) => + path is "/login" or "/logout" or "/api/health" or "/icon.svg" or "/manifest.webmanifest" || + path.StartsWith("/css/", StringComparison.Ordinal) || + path.StartsWith("/img/", StringComparison.Ordinal); + + private static Func Auth(string password) { - string path = http.Request.Path.Value ?? "/"; - if (token.Length == 0 || path == "/api/health" || path == "/login" || path == "/icon.svg" || path == "/manifest.webmanifest") + string session = password.Length > 0 ? SessionValue(password) : string.Empty; + return async (http, next) => { - await next(http).ConfigureAwait(false); - return; - } + string path = http.Request.Path.Value ?? "/"; + if (password.Length == 0 || IsPublic(path)) + { + await next(http).ConfigureAwait(false); + return; + } - bool ok = (http.Request.Cookies.TryGetValue(CookieName, out string? cookie) && Constant(cookie, token)) - || (http.Request.Headers.Authorization.ToString() is { Length: > 7 } auth && auth.StartsWith("Bearer ", StringComparison.Ordinal) && Constant(auth[7..].Trim(), token)); - if (ok) - { - await next(http).ConfigureAwait(false); - return; - } + bool ok = (http.Request.Cookies.TryGetValue(CookieName, out string? cookie) && Constant(cookie, session)) + || (http.Request.Headers.Authorization.ToString() is { Length: > 7 } auth && auth.StartsWith("Bearer ", StringComparison.Ordinal) && Constant(auth[7..].Trim(), password)); + if (ok) + { + await next(http).ConfigureAwait(false); + return; + } - if (path.StartsWith("/api/", StringComparison.Ordinal)) - { - http.Response.StatusCode = 401; - await Text(http, Json.Result(false, "token mancante o errato"), "application/json").ConfigureAwait(false); - return; - } + if (path.StartsWith("/api/", StringComparison.Ordinal)) + { + http.Response.StatusCode = 401; + await Text(http, Json.Result(false, "accesso richiesto: password mancante o errata"), "application/json").ConfigureAwait(false); + return; + } - http.Response.Redirect("/login"); - }; + http.Response.Redirect("/login"); + }; + } + /// Equality in constant time, lengths included: both sides are hashed to the same size first. private static bool Constant(string a, string b) { - byte[] x = Encoding.UTF8.GetBytes(a); - byte[] y = Encoding.UTF8.GetBytes(b); - return x.Length == y.Length && CryptographicOperations.FixedTimeEquals(x, y); + byte[] x = SHA256.HashData(Encoding.UTF8.GetBytes(a)); + byte[] y = SHA256.HashData(Encoding.UTF8.GetBytes(b)); + return CryptographicOperations.FixedTimeEquals(x, y); } // ----------------------------------------------------------------------- // Static assets (embedded) // ----------------------------------------------------------------------- - private static void MapStatic(WebApplication app, string token) + private static void MapStatic(WebApplication app, string password) { app.MapGet("/", Serve("wwwroot/index.html", "text/html; charset=utf-8")); app.MapGet("/index.html", Serve("wwwroot/index.html", "text/html; charset=utf-8")); @@ -150,16 +194,46 @@ public static class WebHost app.MapPost("/login", async http => { Dictionary body = await FormOrJsonAsync(http).ConfigureAwait(false); - if (token.Length > 0 && body.TryGetValue("token", out string? given) && Constant(given.Trim(), token)) + + // "password" since 5.1; "token" is the field of the 5.0 login page, still accepted. + string given = (body.GetValueOrDefault("password") is { Length: > 0 } p ? p : body.GetValueOrDefault("token") ?? string.Empty).Trim(); + if (password.Length > 0 && given.Length > 0 && Constant(given, password)) { - http.Response.Cookies.Append(CookieName, token, new CookieOptions { HttpOnly = true, SameSite = SameSiteMode.Strict, IsEssential = true, Path = "/", MaxAge = TimeSpan.FromDays(30) }); + http.Response.Cookies.Append(CookieName, SessionValue(password), new CookieOptions { HttpOnly = true, SameSite = SameSiteMode.Strict, IsEssential = true, Path = "/", MaxAge = TimeSpan.FromDays(30) }); http.Response.Redirect("/"); return; } + await Task.Delay(FailedLoginDelay, http.RequestAborted).ConfigureAwait(false); http.Response.StatusCode = 401; - await Text(http, "

Token errato. Riprova.

", "text/html; charset=utf-8").ConfigureAwait(false); + 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); }); + app.MapPost("/logout", http => + { + http.Response.Cookies.Delete(CookieName, new CookieOptions { HttpOnly = true, SameSite = SameSiteMode.Strict, Path = "/" }); + http.Response.Redirect("/login"); + return Task.CompletedTask; + }); + } + + /// The login page with the message of a failed attempt: in its placeholder, before the end of its form, or on its own. + private static string LoginPageWithError(string message) + { + string alert = $"

{WebUtility.HtmlEncode(message)}

"; + byte[]? page = Asset("wwwroot/login.html"); + if (page is null) + { + return $"{alert}

Riprova.

"; + } + + string html = Encoding.UTF8.GetString(page); + if (html.Contains(LoginErrorPlaceholder, StringComparison.Ordinal)) + { + return html.Replace(LoginErrorPlaceholder, alert, StringComparison.Ordinal); + } + + int form = html.IndexOf("", StringComparison.OrdinalIgnoreCase); + return form >= 0 ? html.Insert(form, alert) : html.Replace("", alert + "", StringComparison.OrdinalIgnoreCase); } /// Reads an embedded asset. Cached in memory after the first read: the assembly is the file system. @@ -246,68 +320,6 @@ public static class WebHost app.MapGet("/api/history/positions", async http => await HistoryPositionsAsync(http, ctx).ConfigureAwait(false)); app.MapGet("/api/history/periods", async http => await HistoryPeriodsAsync(http, ctx).ConfigureAwait(false)); - app.MapGet("/api/settings", async http => - { - EncryptedFileKeyStore store = KeyStores.File(ctx.Config); - bool env = KeyStores.Clean(Environment.GetEnvironmentVariable("ETORO_API_KEY")) is not null; - string keys = env - ? "chiavi dalle variabili d'ambiente ETORO_API_KEY e ETORO_USER_KEY (sola lettura)" - : store.Exists - ? (store.CanSave ? $"chiavi nel file cifrato {store.Path}" : $"file cifrato {store.Path} presente ma manca {KeyStores.PassphraseVariable}: non leggibile") - : (store.CanSave ? $"nessuna chiave salvata; verrà creato {store.Path}" : $"nessuna chiave: imposta ETORO_API_KEY e ETORO_USER_KEY, oppure {KeyStores.PassphraseVariable} per salvarle qui"); - await Text(http, SettingsService.Describe(ctx.Config, ctx.ConfigPath, keys, ctx.Config.Run.StrategyPath), "application/json").ConfigureAwait(false); - }); - app.MapPost("/api/settings", async http => - { - Dictionary edits = await Json.BodyAsync(http.Request.Body, http.RequestAborted).ConfigureAwait(false); - (bool ok, string message, int applied) = SettingsService.Apply(ctx.Config, ctx.ConfigPath, edits); - if (ok && applied > 0) - { - // The UI-only values take effect now: the next snapshot carries them. - foreach ((string path, string value) in edits) - { - if (path.Equals("ui.displayCurrency", StringComparison.OrdinalIgnoreCase)) { ctx.Config.Ui.DisplayCurrency = value.Trim().ToUpperInvariant(); } - if (path.Equals("ui.theme", StringComparison.OrdinalIgnoreCase)) { ctx.Config.Ui.Theme = value.Trim().ToLowerInvariant(); } - if (path.Equals("ui.navExpanded", StringComparison.OrdinalIgnoreCase)) { ctx.Config.Ui.NavExpanded = value is "sì" or "si" or "true"; } - } - - Log.Info(message); - } - - http.Response.StatusCode = ok ? 200 : 400; - await Text(http, Json.Result(ok, message, w => w.WriteNumber("applied", applied)), "application/json").ConfigureAwait(false); - }); - app.MapPost("/api/settings/keys", async http => await SaveKeysAsync(http, ctx).ConfigureAwait(false)); - app.MapDelete("/api/settings/keys", async http => - { - bool removed = KeyStores.File(ctx.Config).Clear(ctx.Config.Etoro.IsDemo); - ctx.Config.Etoro.ApiKey = string.Empty; - ctx.Config.Etoro.UserKey = string.Empty; - Log.Info(removed ? "chiavi eToro salvate rimosse" : "non c'erano chiavi eToro salvate da rimuovere"); - await Text(http, Json.Result(true, removed ? "chiavi rimosse" : "nessuna chiave salvata da rimuovere"), "application/json").ConfigureAwait(false); - }); - app.MapPost("/api/settings/restore", async http => - { - if (ctx.Supervisor.State is BotState.Running or BotState.Starting) - { - http.Response.StatusCode = 409; - await Text(http, Json.Result(false, "ferma il bot prima di ripristinare la configurazione"), "application/json").ConfigureAwait(false); - return; - } - - try - { - string? backup = ConfigDefaults.Restore(ctx.ConfigPath); - Log.Info(backup is null ? "configurazione ripristinata ai valori predefiniti" : $"configurazione ripristinata; la precedente è in {backup}"); - await Text(http, Json.Result(true, backup is null ? "configurazione ripristinata; riavvia il container" : $"configurazione ripristinata (copia precedente in {backup}); riavvia il container"), "application/json").ConfigureAwait(false); - } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) - { - http.Response.StatusCode = 500; - await Text(http, Json.Result(false, ex.Message), "application/json").ConfigureAwait(false); - } - }); - app.MapGet("/api/info", async http => await Text(http, Info(ctx), "application/json").ConfigureAwait(false)); app.MapGet("/api/research", async http => await Text(http, Research(ctx), "application/json").ConfigureAwait(false)); } @@ -361,7 +373,7 @@ public static class WebHost "stop" => await ctx.Supervisor.StopAsync().ConfigureAwait(false), "close" => await ctx.Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.Close, arg, reason.Length > 0 ? reason : "chiusura manuale dalla web UI"), ct).ConfigureAwait(false), "kill" => await ctx.Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.KillSwitch, body.GetValueOrDefault("foreign") is "true" or "1" ? "esterne" : string.Empty, "kill-switch dalla web UI"), ct).ConfigureAwait(false), - "preset" => await ctx.Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.SetPreset, arg, "cambio preset dalla web UI"), ct).ConfigureAwait(false), + "preset" => new CommandResult(false, "il comando preset non esiste più: il preset si sceglie in Impostazioni ▸ Strategia"), "reset" => await ctx.Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.ResetEquityStop, string.Empty, reason), ct).ConfigureAwait(false), "residue" => await ctx.Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.CloseResidue, arg.Length > 0 ? arg : "all", "chiusura dei residui dalla web UI"), ct).ConfigureAwait(false), "pause" => await ctx.Supervisor.ExecuteAsync(new EngineCommand(EngineCommandKind.Pause, string.Empty, "pausa dalla web UI"), ct).ConfigureAwait(false), @@ -372,9 +384,15 @@ public static class WebHost }; } - http.Response.StatusCode = result.Ok ? 200 : 400; + http.Response.StatusCode = result.Ok ? 200 : result.Code == CommandResult.NeedsPhrase ? 409 : 400; await Text(http, Json.Result(result.Ok, result.Message, w => { + w.WriteBoolean("needsPhrase", result.Code == CommandResult.NeedsPhrase); + if (result.Code.Length > 0) + { + w.WriteString("code", result.Code); + } + if (result.Payload is IReadOnlyList positions) { w.WriteStartArray("positions"); @@ -545,48 +563,6 @@ public static class WebHost }), "application/json").ConfigureAwait(false); } - private static async Task SaveKeysAsync(HttpContext http, WebContext ctx) - { - Dictionary body = await Json.BodyAsync(http.Request.Body, http.RequestAborted).ConfigureAwait(false); - string? api = KeyStores.Clean(body.GetValueOrDefault("apiKey")); - string? user = KeyStores.Clean(body.GetValueOrDefault("userKey")); - if (api is null || user is null) - { - http.Response.StatusCode = 400; - await Text(http, Json.Result(false, "servono entrambe le chiavi (x-api-key e x-user-key)"), "application/json").ConfigureAwait(false); - return; - } - - EncryptedFileKeyStore store = KeyStores.File(ctx.Config); - if (!store.CanSave) - { - http.Response.StatusCode = 400; - await Text(http, Json.Result(false, $"nessuna passphrase nell'ambiente ({KeyStores.PassphraseVariable}): le chiavi non possono essere salvate su file; usa ETORO_API_KEY e ETORO_USER_KEY"), "application/json").ConfigureAwait(false); - return; - } - - // Verified before being saved: a wrong pair costs a 401 at the next start, and that is the worst moment. - EtoroOptions options = new() { Environment = ctx.Config.Etoro.Environment, BaseUrl = ctx.Config.Etoro.BaseUrl, ApiKey = api, UserKey = user, UserAgent = ctx.Config.Etoro.UserAgent }; - try - { - using CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(http.RequestAborted); - cts.CancelAfter(TimeSpan.FromSeconds(20)); - await using EtoroBroker broker = new(options); - string username = await broker.VerifyAsync(cts.Token).ConfigureAwait(false); - AccountSnapshot account = await broker.GetAccountAsync(cts.Token).ConfigureAwait(false); - store.Save(ctx.Config.Etoro.IsDemo, new EtoroKeys(api, user, DateTime.UtcNow)); - ctx.Config.Etoro.ApiKey = api; - ctx.Config.Etoro.UserKey = user; - Log.Info($"chiavi eToro verificate ({KeyStores.Mask(api)}, utente {username}) e salvate in {store.Path}"); - await Text(http, Json.Result(true, string.Create(CultureInfo.InvariantCulture, $"chiavi verificate: utente {username}, equity {account.Equity:N2} {account.Currency}; salvate in {store.Path}")), "application/json").ConfigureAwait(false); - } - catch (Exception ex) when (ex is BrokerException or HttpRequestException or OperationCanceledException or InvalidOperationException) - { - http.Response.StatusCode = 400; - await Text(http, Json.Result(false, $"eToro ha rifiutato le chiavi o non risponde: {ex.Message}"), "application/json").ConfigureAwait(false); - } - } - // ----------------------------------------------------------------------- // Health, info, research // ----------------------------------------------------------------------- @@ -666,22 +642,13 @@ public static class WebHost private static string Research(WebContext ctx) { BotSnapshot s = ctx.Snapshot(); - BasketStrategyConfig? strategy = null; - try - { - strategy = File.Exists(ctx.Config.Run.StrategyPath) ? BasketStrategyConfig.Load(ctx.Config.Run.StrategyPath, out _) : null; - } - catch (Exception ex) when (ex is IOException or InvalidOperationException or JsonException) - { - Log.Warn($"strategy.json non leggibile: {ex.Message}"); - } - + BasketStrategyConfig strategy = ctx.Settings.Strategy.Current(); string knowledge = ctx.Config.Run.KnowledgePath; return Json.Object(w => { - w.WriteBoolean("learningEnabled", strategy?.Learning.Enabled ?? false); - w.WriteBoolean("weeklyCycle", strategy?.Learning.WeeklyCycle ?? false); - w.WriteBoolean("challenger", strategy?.Learning.Challenger ?? false); + w.WriteBoolean("learningEnabled", strategy.Learning.Enabled); + w.WriteBoolean("weeklyCycle", strategy.Learning.WeeklyCycle); + w.WriteBoolean("challenger", strategy.Learning.Challenger); w.WriteString("mlState", s.Context?.MlState ?? "—"); w.WriteString("banditProposal", s.Context?.BanditProposal ?? "—"); w.WriteString("volForecast", s.Context?.VolForecast ?? "—"); diff --git a/Encelado/tests/Encelado.Tests/BasketTests.cs b/Encelado/tests/Encelado.Tests/BasketTests.cs index 8322434..4c41bfc 100644 --- a/Encelado/tests/Encelado.Tests/BasketTests.cs +++ b/Encelado/tests/Encelado.Tests/BasketTests.cs @@ -548,8 +548,8 @@ public sealed class LedgerTests : IDisposable BasketDecision skip = new(DecisionKind.Skip, false, null, ["no_signal"], "|z| 0,4 sotto zIn 2", new BasketEvaluation { Z = 0.4, RhoW = -0.7 }, null); BasketDecision enter = new(DecisionKind.Enter, true, new SizingResult(true, 1000, 900, 1100, 1000, 50, 2, "ok"), ["enter"], "entro", new BasketEvaluation { Z = -2.3, RhoW = -0.75, CostPips = 3.2 }, null); - ledger.Decision("run1", "Paper", "MODERATE", "abcd", Context(t), skip, "skip", null); - ledger.Decision("run1", "Paper", "MODERATE", "abcd", Context(t.AddMinutes(15)), enter, "ingresso", "B1"); + ledger.Decision("run1", "Demo", "MODERATE", "abcd", Context(t), skip, "skip", null); + ledger.Decision("run1", "Demo", "MODERATE", "abcd", Context(t.AddMinutes(15)), enter, "ingresso", "B1"); ledger.Correction("run1", "B1", "prova di correzione"); string[] lines = [.. ledger.ReadDecisionLines()]; @@ -561,7 +561,7 @@ public sealed class LedgerTests : IDisposable Assert.Contains("\"evento\":\"correzione\"", lines[2], StringComparison.Ordinal); // Appending again never rewrites what was there. - ledger.Decision("run1", "Paper", "MODERATE", "abcd", Context(t.AddMinutes(30)), skip, "skip", null); + ledger.Decision("run1", "Demo", "MODERATE", "abcd", Context(t.AddMinutes(30)), skip, "skip", null); string[] again = [.. ledger.ReadDecisionLines()]; Assert.Equal(4, again.Length); Assert.Equal(lines, again[..3]); @@ -572,7 +572,7 @@ public sealed class LedgerTests : IDisposable { using Ledger ledger = new(_dir); DateTime t = new(2026, 9, 16, 10, 0, 0, DateTimeKind.Utc); - BasketOutcomeRow row = new("B1", "run1", "EURUSD/USDCHF", "Paper", "MODERATE", t, t.AddHours(3), true, -2.3, -0.2, 12.5, 9.1, 8.0, 3.2, 3.4, 0.6, 0, 12, "tp_pips", 10_000, double.NaN, "take-profit; ingresso: z −2,3"); + BasketOutcomeRow row = new("B1", "run1", "EURUSD/USDCHF", "Demo", "MODERATE", t, t.AddHours(3), true, -2.3, -0.2, 12.5, 9.1, 8.0, 3.2, 3.4, 0.6, 0, 12, "tp_pips", 10_000, double.NaN, "take-profit; ingresso: z −2,3"); ledger.Basket(row); List rows = ledger.ReadBaskets(); diff --git a/Encelado/tests/Encelado.Tests/ConfigurationTests.cs b/Encelado/tests/Encelado.Tests/ConfigurationTests.cs index be17c40..d53f025 100644 --- a/Encelado/tests/Encelado.Tests/ConfigurationTests.cs +++ b/Encelado/tests/Encelado.Tests/ConfigurationTests.cs @@ -78,17 +78,35 @@ public class ConfigDefaultsTests } [Fact] - public void TheDefaultRunsOnTheDemoAccountWithoutLive() + public void TheDefaultRunsOnTheDemoAccountWithoutLiveAndStartsByItself() { BotConfig config = ConfigDefaults.Parse(); config.Validate(); Assert.True(config.Etoro.IsDemo); + Assert.Equal("demo", config.Etoro.Environment); Assert.Equal(ExecutionMode.Demo, config.Run.Mode); Assert.False(config.Run.AllowLive, "il reale non deve mai essere abilitato di fabbrica"); + Assert.True(config.Run.Autostart); Assert.False(config.Run.CloseOnShutdown); Assert.Equal(UiOptions.ComputerZone, config.Ui.TimeZone); + Assert.False(config.Etoro.HasKeys); + } + + /// 5.1: the factory file says nothing of Paper, of the account as a separate setting, or of environment variables. + [Fact] + public void TheDefaultHasNoPaperNoEnvironmentAndNoVariables() + { + Assert.DoesNotContain("paper", ConfigDefaults.Json, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("\"environment\"", ConfigDefaults.Json, StringComparison.Ordinal); + Assert.DoesNotContain("apiKey", ConfigDefaults.Json, StringComparison.Ordinal); + foreach (string variable in EnvironmentImport.LegacyVariables.Append(InterfacePassword.LegacyVariable)) + { + Assert.DoesNotContain(variable, ConfigDefaults.Json, StringComparison.Ordinal); + } + + Assert.DoesNotContain("paper", BasketStrategyConfig.DefaultJson, StringComparison.OrdinalIgnoreCase); } [Fact] @@ -151,7 +169,7 @@ public class ConfigDefaultsTests public class ConfigLoaderTests { - private static BotConfig Load(string json, out List warnings) + internal static BotConfig Load(string json, out List warnings) { string path = Path.Combine(Path.GetTempPath(), $"encelado-{Guid.NewGuid():N}.json"); try @@ -169,16 +187,21 @@ public class ConfigLoaderTests public void ReadsTheEtoroRunAndUiSections() { BotConfig config = Load(""" - { "etoro": { "environment": "real", "fillTimeoutSeconds": 7 }, "run": { "executionMode": "paper", "pollSeconds": 4, "allowLive": true, "closeOnShutdown": true }, "ui": { "timeZone": "UTC" } } + { "etoro": { "fillTimeoutSeconds": 7 }, "run": { "executionMode": "Live", "pollSeconds": 4, "allowLive": true, "closeOnShutdown": true, "autostart": false }, "ui": { "timeZone": "UTC" } } """, out List warnings); Assert.Empty(warnings); - Assert.False(config.Etoro.IsDemo); Assert.Equal(7, config.Etoro.FillTimeoutSeconds); - Assert.Equal(ExecutionMode.Paper, config.Run.Mode); + Assert.Equal(ExecutionMode.Live, config.Run.Mode); Assert.Equal(4, config.Run.PollSeconds); Assert.True(config.Run.CloseOnShutdown); + Assert.False(config.Run.Autostart); Assert.Equal(TimeZoneInfo.Utc, config.Ui.ResolveTimeZone(out _)); + + // The account follows the mode: Live is the real account, and nothing else can pick it. + config.Validate(); + Assert.False(config.Etoro.IsDemo); + Assert.Equal("real", config.Etoro.Environment); } [Fact] @@ -204,6 +227,39 @@ public class ConfigLoaderTests Assert.Contains(warnings, static w => w.Contains("allowDemoAuto", StringComparison.Ordinal)); } + /// Paper is gone (5.1, decision C5): an old file loads as Demo, says so, and its simulator keys are reported. + [Fact] + public void APaperFileOfThePreviousVersionLoadsAsDemoWithAWarning() + { + BotConfig config = Load("""{ "run": { "executionMode": "Paper", "paperStartingBalance": 10000, "paperSlippagePips": 0.3 } }""", out List warnings); + + Assert.Equal(ExecutionMode.Demo, config.Run.Mode); + Assert.Contains(warnings, static w => w.Contains("Paper", StringComparison.Ordinal) && w.Contains("non esiste più", StringComparison.Ordinal)); + Assert.Contains(warnings, static w => w.Contains("paperStartingBalance", StringComparison.Ordinal)); + config.Validate(); + Assert.True(config.Etoro.IsDemo); + } + + /// + /// The merge rule of 5.1 for files of 5.0 (decision C6): Live only when the mode said Live + /// and the account said real. Demo + real — orders to the real account without the Live + /// gate — becomes Demo. + /// + [Theory] + [InlineData("Demo", "demo", ExecutionMode.Demo, false)] + [InlineData("Live", "real", ExecutionMode.Live, false)] + [InlineData("Demo", "real", ExecutionMode.Demo, true)] + [InlineData("Live", "demo", ExecutionMode.Demo, true)] + public void TheModeAndTheAccountOfAPreviousFileMerge(string mode, string environment, ExecutionMode expected, bool disagree) + { + BotConfig config = Load($$"""{ "etoro": { "environment": "{{environment}}" }, "run": { "executionMode": "{{mode}}", "allowLive": true } }""", out List warnings); + + Assert.Equal(expected, config.Run.Mode); + Assert.Contains(warnings, w => w.Contains(disagree ? "non erano d'accordo" : "etoro.environment non esiste più", StringComparison.Ordinal)); + config.Validate(); + Assert.Equal(expected == ExecutionMode.Live ? "real" : "demo", config.Etoro.Environment); + } + [Fact] public void ReportsAPreviousVersionFileAsSomethingToUpgradeRatherThanATypo() { @@ -258,16 +314,74 @@ public class ConfigLoaderTests Assert.Empty(warnings); } + /// Secrets never enter the configuration from a file (5.1): they are reported, and the import moves them to the store. [Fact] - public void KeysNeverComeFromTheMainFileByAccidentButTheOverlayIsAccepted() + public void KeysInAFileAreIgnoredWithAWarning() { - BotConfig config = Load("""{ "etoro": { "apiKey": "a", "userKey": "u" } }""", out List warnings); + BotConfig config = Load("""{ "etoro": { "apiKey": "a", "userKey": "u" }, "notifications": { "telegram": { "botToken": "t" } } }""", out List warnings); - // The loader accepts them (that is how a *.local.json overlay works); the shipped - // file simply never contains them, which the defaults test guarantees. - Assert.Empty(warnings); - Assert.True(config.Etoro.HasKeys); - Assert.DoesNotContain("apiKey\":", ConfigDefaults.Json, StringComparison.Ordinal); + Assert.False(config.Etoro.HasKeys); + Assert.Equal(string.Empty, config.Notifications.Telegram.BotToken); + Assert.Contains(warnings, static w => w.Contains("etoro.apiKey", StringComparison.Ordinal) && w.Contains("secrets.enc", StringComparison.Ordinal)); + Assert.Contains(warnings, static w => w.Contains("botToken", StringComparison.Ordinal)); + } + + /// + /// The variables of 5.0 no longer change a setting at load (they reverted the choices made + /// in the interface at every container restart). Setting one in this process is safe: + /// since 5.1 nothing but the import (which takes the environment as an argument) reads it. + /// + [Fact] + public void TheEnvironmentNoLongerOverridesTheFile() + { + string? previous = Environment.GetEnvironmentVariable("ENCELADO_DISPLAY_CURRENCY"); + try + { + Environment.SetEnvironmentVariable("ENCELADO_DISPLAY_CURRENCY", "JPY"); + BotConfig config = Load("""{ "ui": { "displayCurrency": "EUR" } }""", out _); + Assert.Equal("EUR", config.Ui.DisplayCurrency); + } + finally + { + Environment.SetEnvironmentVariable("ENCELADO_DISPLAY_CURRENCY", previous); + } + } + + [Fact] + public void CopyFromTakesTheEditableValuesAndKeepsTheFoldersAndTheEndpoints() + { + BotConfig live = ConfigDefaults.Parse(); + live.Run.BaseDirectory = "/config"; + live.Run.DataDirectory = "/data/data"; + live.Logging.Directory = "/data/logs"; + BotConfig fresh = Load(""" + { "etoro": { "baseUrl": "https://altro.example", "fillTimeoutSeconds": 9 }, + "run": { "executionMode": "Live", "allowLive": true, "autostart": false, "pollSeconds": 7, "dataDirectory": "altrove" }, + "ui": { "displayCurrency": "CHF", "theme": "light" }, + "logging": { "level": "debug", "directory": "altri-log", "bufferedLines": 800 }, + "notifications": { "telegram": { "enabled": true, "chatId": "42" } } } + """, out _); + + Core.Notifications.TelegramOptions telegram = live.Notifications.Telegram; + live.CopyFrom(fresh); + + Assert.Equal(ExecutionMode.Live, live.Run.Mode); + Assert.Equal("real", live.Etoro.Environment); + Assert.True(live.Run.AllowLive); + Assert.False(live.Run.Autostart); + Assert.Equal(7, live.Run.PollSeconds); + Assert.Equal(9, live.Etoro.FillTimeoutSeconds); + Assert.Equal("CHF", live.Ui.DisplayCurrency); + Assert.Equal("debug", live.Logging.Level); + Assert.Equal(800, live.Logging.BufferedLines); + Assert.Same(telegram, live.Notifications.Telegram); + Assert.True(telegram.Enabled); + Assert.Equal("42", telegram.ChatId); + + Assert.Equal("/config", live.Run.BaseDirectory); + Assert.Equal("/data/data", live.Run.DataDirectory); + Assert.Equal("/data/logs", live.Logging.Directory); + Assert.Equal(Encelado.Etoro.EtoroOptions.DefaultBaseUrl, live.Etoro.BaseUrl); } } @@ -276,7 +390,7 @@ public class ExecutionModeTests [Theory] [InlineData("demo", ExecutionMode.Demo)] [InlineData("Demo", ExecutionMode.Demo)] - [InlineData("paper", ExecutionMode.Paper)] + [InlineData("paper", ExecutionMode.Demo)] [InlineData("live", ExecutionMode.Live)] [InlineData("real", ExecutionMode.Live)] [InlineData("demo-auto", ExecutionMode.Demo)] @@ -294,23 +408,44 @@ public class ExecutionModeTests } [Fact] - public void OnlyLiveIsLive() + public void OnlyLiveIsLiveAndPaperIsALegacyName() { Assert.True(ExecutionMode.Live.IsLive()); Assert.False(ExecutionMode.Demo.IsLive()); - Assert.False(ExecutionMode.Paper.IsLive()); Assert.True(ExecutionMode.Demo.UsesVenue()); - Assert.False(ExecutionMode.Paper.UsesVenue()); Assert.Equal("demo", ExecutionMode.Demo.Kind()); + Assert.Equal("live", ExecutionMode.Live.Account()); + Assert.Equal("demo", ExecutionMode.Demo.Account()); + Assert.True(ExecutionModeExtensions.IsLegacyName("Paper")); + Assert.Equal(["Backtest", "Demo", "Live"], Enum.GetNames()); + } + + [Theory] + [InlineData(ExecutionMode.Live, "real", ExecutionMode.Live, false)] + [InlineData(ExecutionMode.Live, "demo", ExecutionMode.Demo, true)] + [InlineData(ExecutionMode.Demo, "real", ExecutionMode.Demo, true)] + [InlineData(ExecutionMode.Demo, null, ExecutionMode.Demo, false)] + public void TheMergeRuleNeedsBothToSayLive(ExecutionMode mode, string? environment, ExecutionMode expected, bool disagree) + { + Assert.Equal(expected, ExecutionModeExtensions.Merge(mode, environment, out bool d)); + Assert.Equal(disagree, d); } } public class SettingsFormTests { - private static BotConfig Config() => ConfigDefaults.Parse(); + private static IReadOnlyList Groups() => + SettingsCatalogue.Build(ConfigDefaults.Parse(), BasketStrategyConfig.ParseText(BasketStrategyConfig.DefaultJson, out _)); - private static IReadOnlyList Fields() => - [.. SettingsCatalogue.Build(Config()).SelectMany(static g => g.Fields)]; + private static IReadOnlyList Fields() => [.. Groups().SelectMany(static g => g.Fields)]; + + [Fact] + public void TheGroupsAreThoseOfTheDecision() + { + Assert.Equal(["conto", "esecuzione", "strategia", "avanzate", "telegram", "interfaccia", "log"], Groups().Select(static g => g.Key)); + Assert.True(Groups().Single(static g => g.Key == "avanzate").Advanced); + Assert.All(Groups().Where(static g => g.Key is "strategia" or "avanzate"), static g => Assert.Equal(SettingTarget.Strategy, g.Target)); + } [Fact] public void EveryFieldStartsCleanOnTheFactoryConfiguration() @@ -325,57 +460,137 @@ public class SettingsFormTests [Theory] [InlineData("logging.level")] - [InlineData("etoro.environment")] [InlineData("run.executionMode")] - [InlineData("ui.timeZone")] + [InlineData("strategy:preset")] + [InlineData("ui.displayCurrency")] public void ClosedSetsAreChosenFromAListRatherThanTyped(string path) { SettingField field = Fields().First(f => f.Path == path); - Assert.True(field.IsList, $"{path} deve essere un elenco"); - Assert.NotEmpty(field.Options); - Assert.False(field.IsObsolete, - $"{path} vale '{field.Value}' che non è fra {string.Join(", ", field.Options.Take(5))}…"); + Assert.Equal(SettingKind.Choice, field.Kind); + Assert.Equal("choice", field.KindName); + Assert.Contains(field.Value, field.Options); } [Fact] - public void TheTimeZoneListStartsWithTheComputerAndUtc() + public void TheAccountIsDemoOrLiveAndPaperAndTheEnvironmentAreGone() { - SettingField field = Fields().First(static f => f.Path == "ui.timeZone"); - - Assert.Equal("computer", field.Options[0]); - Assert.Equal("UTC", field.Options[1]); - Assert.True(field.Options.Count > 10, "l'elenco deve contenere i fusi di Windows"); + SettingField mode = Fields().First(static f => f.Path == "run.executionMode"); + Assert.Equal(["Demo", "Live"], mode.Options); + Assert.DoesNotContain(Fields(), static f => f.Path.Contains("paper", StringComparison.OrdinalIgnoreCase) || f.Path == "etoro.environment" || f.Path == "ui.timeZone"); + Assert.Equal(["Conservative", "Moderate", "Aggressive"], Fields().First(static f => f.Path == "strategy:preset").Options); } [Fact] - public void BooleansAreAListToo() + public void BooleansTravelAsTrueOrFalseAndAcceptTheItalianWords() { SettingField field = Fields().First(static f => f.Path == "run.allowLive"); - Assert.True(field.IsList); - Assert.Equal(["sì", "no"], field.Options); + Assert.Equal("bool", field.KindName); + Assert.Equal("false", field.Value); + Assert.Empty(field.Options); + field.Value = "sì"; + Assert.Equal("true", field.Value); + Assert.False(field.HasError); + Assert.True(field.IsDirty); + field.Value = "forse"; + Assert.True(field.HasError); } [Fact] - public void NumbersStayFreeText() + public void NumbersAcceptADecimalCommaAndStayInRange() { - Assert.True(Fields().First(static f => f.Path == "run.pollSeconds").IsFreeText); + SettingField poll = Fields().First(static f => f.Path == "run.pollSeconds"); + Assert.Equal("integer", poll.KindName); + poll.Value = "40"; + Assert.True(poll.HasError); + + SettingField rho = Fields().First(static f => f.Path == "strategy:rhoMin"); + rho.Value = "0,65"; + Assert.False(rho.HasError); + Assert.Equal("0.65", rho.Value); + Assert.Equal(0.65, rho.ToJson()!.GetValue(), 10); + } + + [Fact] + public void AnOverrideLeftEmptyIsTheDeletionOfItsKey() + { + SettingField zIn = Fields().First(static f => f.Path == "strategy:zIn"); + + Assert.Equal(string.Empty, zIn.Value); + Assert.True(zIn.AllowEmpty); + zIn.Value = "2.2"; + Assert.True(zIn.IsDirty); + Assert.False(zIn.IsDeletion); + zIn.Value = string.Empty; + Assert.False(zIn.IsDirty); + Assert.True(zIn.IsDeletion); + } + + [Fact] + public void TheSessionsAreAListOfUtcRanges() + { + SettingField sessions = Fields().First(static f => f.Path == "strategy:sessions"); + Assert.Equal("list", sessions.KindName); + sessions.Value = "07-16, 20-22"; + Assert.False(sessions.HasError); + Assert.Equal("07-16,20-22", sessions.Value); + Assert.Equal(2, sessions.ToJson()!.AsArray().Count); + sessions.Value = "sera"; + Assert.True(sessions.HasError); + } + + /// What only a fresh engine can take: the account, the pairs, the direct crosses. Everything else is applied hot. + [Fact] + public void OnlyTheAccountAndTheInstrumentsNeedARestart() + { + List restart = [.. Fields().Where(static f => f.Scope == SettingScope.Restart).Select(static f => f.Path)]; + + Assert.Contains("run.executionMode", restart); + Assert.Contains("strategy:preferDirectCross", restart); + Assert.Contains("strategy:baskets[0].a", restart); + Assert.All(restart, static p => Assert.True(p == "run.executionMode" || p == "strategy:preferDirectCross" || (p.StartsWith("strategy:baskets[", StringComparison.Ordinal) && !p.EndsWith(".enabled", StringComparison.Ordinal)), p)); + Assert.Equal(SettingScope.Engine, Fields().First(static f => f.Path == "strategy:preset").Scope); + Assert.Equal(SettingScope.Engine, Fields().First(static f => f.Path == "strategy:baskets[2].enabled").Scope); + Assert.Equal(SettingScope.Immediate, Fields().First(static f => f.Path == "logging.level").Scope); + } + + /// Since 5.1 everything is set from the interface: no text sends the operator to an environment variable. + [Fact] + public void NoTextMentionsAnEnvironmentVariable() + { + foreach (SettingGroup g in Groups()) + { + foreach (string text in g.Fields.Select(static f => f.FullTooltip + " " + f.Label).Append(g.Description)) + { + Assert.DoesNotContain("ENCELADO_", text, StringComparison.Ordinal); + Assert.DoesNotContain("ETORO_", text, StringComparison.Ordinal); + Assert.DoesNotContain("TELEGRAM_", text, StringComparison.Ordinal); + Assert.DoesNotContain("variabil", text, StringComparison.OrdinalIgnoreCase); + } + } } /// - /// Every path the form can write must actually resolve in the shipped file. A typo - /// here is invisible until someone saves and the value silently lands in the wrong - /// place — or creates a key nothing reads. + /// Every path the form can write must resolve in its own shipped file. A typo here is + /// invisible until someone saves and the value silently lands in the wrong place — or + /// creates a key nothing reads. The preset overrides are optional keys: absent is "the preset". /// [Fact] - public void EveryEditablePathExistsInTheShippedConfiguration() + public void EveryEditablePathExistsInItsShippedFile() { - JsonNode root = JsonNode.Parse(ConfigDefaults.Json)!; + JsonNode config = JsonNode.Parse(ConfigDefaults.Json)!; + JsonNode strategy = JsonNode.Parse(BasketStrategyConfig.DefaultJson)!; foreach (SettingField field in Fields().Where(static f => !f.IsReadOnly)) { - Assert.True(Resolves(root, field.Path), $"il percorso '{field.Path}' non esiste nel file"); + if (field.AllowEmpty && field.Kind is SettingKind.Integer or SettingKind.Number) + { + continue; + } + + JsonNode root = field.Target == SettingTarget.Strategy ? strategy : config; + Assert.True(Resolves(root, field.FilePath), $"il percorso '{field.Path}' non esiste nel suo file"); } static bool Resolves(JsonNode root, string path) @@ -384,7 +599,15 @@ public class SettingsFormTests foreach (string segment in path.Split('.', StringSplitOptions.RemoveEmptyEntries)) { - current = current is JsonObject o && o.TryGetPropertyValue(segment, out JsonNode? child) ? child : null; + int bracket = segment.IndexOf('[', StringComparison.Ordinal); + string name = bracket < 0 ? segment : segment[..bracket]; + current = current is JsonObject o && o.TryGetPropertyValue(name, out JsonNode? child) ? child : null; + if (bracket >= 0 && current is JsonArray a) + { + int index = int.Parse(segment[(bracket + 1)..^1], System.Globalization.CultureInfo.InvariantCulture); + current = index < a.Count ? a[index] : null; + } + if (current is null) { return false; @@ -396,6 +619,86 @@ public class SettingsFormTests } } +public class ConfigWriterTests : IDisposable +{ + private readonly string _path = Path.Combine(Path.GetTempPath(), $"encelado-writer-{Guid.NewGuid():N}.json"); + + public void Dispose() + { + if (File.Exists(_path)) + { + File.Delete(_path); + } + } + + [Fact] + public void KeysAreRemovedAndMissingOnesAreNotAnError() + { + File.WriteAllText(_path, """{ "etoro": { "environment": "real", "baseUrl": "https://x.example" }, "run": { "_paper": "doc", "paperSlippagePips": 0.3, "pollSeconds": 3 } }"""); + + ConfigWriter.Apply(_path, new Dictionary { ["run.pollSeconds"] = JsonValue.Create(5) }, ["etoro.environment", "run._paper", "run.paperSlippagePips", "run.nonEsiste", "manca.del.tutto"]); + + JsonNode root = JsonNode.Parse(File.ReadAllText(_path))!; + Assert.Null(root["etoro"]!["environment"]); + Assert.Equal("https://x.example", root["etoro"]!["baseUrl"]!.GetValue()); + Assert.Null(root["run"]!["_paper"]); + Assert.Null(root["run"]!["paperSlippagePips"]); + Assert.Equal(5, root["run"]!["pollSeconds"]!.GetValue()); + Assert.True(ConfigWriter.Contains(_path, "run.pollSeconds")); + Assert.False(ConfigWriter.Contains(_path, "etoro.environment")); + } + + /// Accented letters and symbols stay readable in a hand-edited file (5.1, decision C13). + [Fact] + public void NonAsciiTextStaysReadable() + { + File.WriteAllText(_path, """{ "_nota": "modalità: ρ ≥ 0,6 × l'equity", "preset": "Moderate" }"""); + + ConfigWriter.Apply(_path, new Dictionary { ["preset"] = JsonValue.Create("Aggressive") }); + + string text = File.ReadAllText(_path); + Assert.Contains("modalità: ρ ≥ 0,6 × l'equity", text, StringComparison.Ordinal); + Assert.DoesNotContain("\\u", text, StringComparison.Ordinal); + Assert.Contains("\"Aggressive\"", text, StringComparison.Ordinal); + } + + /// A file of 5.0 keeps explaining variables that are no longer read: a save refreshes those lines, never the values. + [Fact] + public void TheDocumentationLinesOfAnOlderFileAreRefreshedAndTheValuesAreNot() + { + File.WriteAllText(_path, """ + { "_commento": "vecchio", "run": { "_executionMode": "Paper = simulatore", "executionMode": "Demo", "_mia": "nota mia" }, + "notifications": { "_telegram": "variabile TELEGRAM_BOT_TOKEN", "telegram": { "enabled": true } } } + """); + + Dictionary updates = ConfigWriter.DocumentationUpdates(_path, ConfigDefaults.Json); + + Assert.Equal(["_commento", "run._executionMode", "notifications._telegram"], updates.Keys); + ConfigWriter.Apply(_path, updates); + BotConfig loaded = ConfigLoader.Load(_path, out _); + Assert.True(loaded.Notifications.Telegram.Enabled); + string text = File.ReadAllText(_path); + Assert.DoesNotContain("TELEGRAM_BOT_TOKEN", text, StringComparison.Ordinal); + Assert.DoesNotContain("Paper", text, StringComparison.Ordinal); + Assert.Contains("nota mia", text, StringComparison.Ordinal); + } + + [Fact] + public void ArrayElementsAreEditedInPlace() + { + File.WriteAllText(_path, BasketStrategyConfig.DefaultJson); + + ConfigWriter.Apply(_path, new Dictionary { ["baskets[2].enabled"] = JsonValue.Create(false), ["risk.maxMarginUsePct"] = JsonValue.Create(35) }); + + BasketStrategyConfig s = BasketStrategyConfig.Load(_path, out List warnings); + Assert.Empty(warnings); + Assert.False(s.Baskets[2].Enabled); + Assert.True(s.Baskets[1].Enabled); + Assert.Equal(35, s.Risk.MaxMarginUsePct); + Assert.Throws(() => ConfigWriter.Apply(_path, new Dictionary { ["baskets[9].enabled"] = JsonValue.Create(false) })); + } +} + public class UiClockTests { [Fact] diff --git a/Encelado/tests/Encelado.Tests/CorrectionTests.cs b/Encelado/tests/Encelado.Tests/CorrectionTests.cs index 61801d8..becada5 100644 --- a/Encelado/tests/Encelado.Tests/CorrectionTests.cs +++ b/Encelado/tests/Encelado.Tests/CorrectionTests.cs @@ -77,6 +77,8 @@ internal sealed class RecordingNotifier : INotifier public string Status => "test"; + public bool IsActive => true; + public void Notify(NotificationKind kind, string title, string text) => Messages.Add((kind, title, text)); } diff --git a/Encelado/tests/Encelado.Tests/EnvironmentImportTests.cs b/Encelado/tests/Encelado.Tests/EnvironmentImportTests.cs new file mode 100644 index 0000000..d422e03 --- /dev/null +++ b/Encelado/tests/Encelado.Tests/EnvironmentImportTests.cs @@ -0,0 +1,222 @@ +using System.Text.Json.Nodes; +using Encelado.Core.Baskets; +using Encelado.Engine.Configuration; + +namespace Encelado.Tests; + +/// +/// The one-time import of a 5.0 container's variables (decision C4): secrets into empty +/// slots of the store, settings only when they differ from the factory default and the file +/// still holds it, the old key file migrated, run once, the leftovers listed as ignored. +/// +public sealed class EnvironmentImportTests : IDisposable +{ + private static readonly DateTime Now = new(2026, 9, 30, 8, 0, 0, DateTimeKind.Utc); + + private readonly string _dir = Path.Combine(Path.GetTempPath(), $"encelado-import-{Guid.NewGuid():N}"); + + public EnvironmentImportTests() + { + Directory.CreateDirectory(_dir); + System.IO.File.WriteAllText(ConfigPath, ConfigDefaults.Json); + } + + public void Dispose() + { + if (Directory.Exists(_dir)) + { + Directory.Delete(_dir, recursive: true); + } + } + + private string ConfigPath => Path.Combine(_dir, "encelado.json"); + + private string Marker => Path.Combine(_dir, EnvironmentImport.MarkerFileName); + + private SecretStore Store(string password = "password") => new(_dir, password, 1_000); + + private static Func Env(params (string Name, string Value)[] vars) => + name => vars.FirstOrDefault(v => v.Name == name).Value; + + private BotConfig Saved() => ConfigLoader.Load(ConfigPath, out _); + + [Fact] + public void TheKeysOfTheEnvironmentGoToTheDemoAccountOfADemoContainer() + { + SecretStore store = Store(); + ImportOutcome o = EnvironmentImport.Run(ConfigPath, store, Env(("ETORO_API_KEY", "api-env"), ("ETORO_USER_KEY", "user-env"), ("ETORO_ENVIRONMENT", "demo"), ("ENCELADO_EXECUTION_MODE", "Demo")), Now); + + Assert.True(o.Ran); + Assert.Equal("api-env", store.Etoro(demo: true)!.ApiKey); + Assert.Null(store.Etoro(demo: false)); + Assert.Contains("ETORO_API_KEY", o.Imported); + Assert.True(System.IO.File.Exists(Marker)); + + // The template's defaults were not an intent: the file is untouched. + Assert.False(o.ConfigChanged); + Assert.Equal(ExecutionMode.Demo, Saved().Run.Mode); + } + + [Fact] + public void LiveAndRealTogetherAreTheRealAccountAndTheLiveMode() + { + ConfigWriter.Apply(ConfigPath, new Dictionary { ["run.allowLive"] = JsonValue.Create(true) }); + SecretStore store = Store(); + + ImportOutcome o = EnvironmentImport.Run(ConfigPath, store, Env(("ETORO_API_KEY", "api-real"), ("ETORO_USER_KEY", "user-real"), ("ETORO_ENVIRONMENT", "real"), ("ENCELADO_EXECUTION_MODE", "Live")), Now); + + Assert.Equal("api-real", store.Etoro(demo: false)!.ApiKey); + Assert.Null(store.Etoro(demo: true)); + Assert.True(o.ConfigChanged); + Assert.Equal(ExecutionMode.Live, Saved().Run.Mode); + Assert.Contains(o.Notes, static n => n.Contains("non parte da solo", StringComparison.Ordinal)); + } + + [Fact] + public void LiveIsNotImportedWhenTheRealAccountIsNotAllowed() + { + ImportOutcome o = EnvironmentImport.Run(ConfigPath, Store(), Env(("ETORO_ENVIRONMENT", "real"), ("ENCELADO_EXECUTION_MODE", "Live")), Now); + + Assert.Equal(ExecutionMode.Demo, Saved().Run.Mode); + Assert.Contains(o.Notes, static n => n.Contains("non importata", StringComparison.Ordinal)); + } + + /// Demo + real sent orders to the real account without the Live gate: the merge rule makes it Demo and says so. + [Fact] + public void DemoWithTheRealEnvironmentIsReadAsDemo() + { + SecretStore store = Store(); + ImportOutcome o = EnvironmentImport.Run(ConfigPath, store, Env(("ETORO_API_KEY", "a"), ("ETORO_USER_KEY", "u"), ("ETORO_ENVIRONMENT", "real"), ("ENCELADO_EXECUTION_MODE", "Demo")), Now); + + Assert.NotNull(store.Etoro(demo: true)); + Assert.Null(store.Etoro(demo: false)); + Assert.Contains(o.Notes, static n => n.Contains("non erano d'accordo", StringComparison.Ordinal)); + Assert.Equal(ExecutionMode.Demo, Saved().Run.Mode); + } + + [Fact] + public void OnlyEmptySlotsAreFilled() + { + SecretStore store = Store(); + store.SaveEtoro(demo: true, new EtoroKeys("api-da-interfaccia", "user-da-interfaccia", Now)); + store.SaveTelegramToken("token-da-interfaccia"); + + ImportOutcome o = EnvironmentImport.Run(ConfigPath, store, Env(("ETORO_API_KEY", "api-env"), ("ETORO_USER_KEY", "user-env"), ("TELEGRAM_BOT_TOKEN", "token-env")), Now); + + Assert.Equal("api-da-interfaccia", store.Etoro(demo: true)!.ApiKey); + Assert.Equal("token-da-interfaccia", store.TelegramToken); + Assert.DoesNotContain("ETORO_API_KEY", o.Imported); + Assert.Contains(o.Notes, static n => n.Contains("già nel deposito", StringComparison.Ordinal)); + } + + [Fact] + public void SettingsAreImportedOnlyWhenTheyDifferFromTheFactoryAndTheFileStillHoldsIt() + { + ConfigWriter.Apply(ConfigPath, new Dictionary { ["logging.level"] = JsonValue.Create("warn") }); + + ImportOutcome o = EnvironmentImport.Run(ConfigPath, Store(), Env( + ("ENCELADO_DISPLAY_CURRENCY", "eur"), + ("ENCELADO_LOG_LEVEL", "debug"), + ("ENCELADO_AUTOSTART", "0"), + ("TELEGRAM_CHAT_ID", "4242"), + ("TZ", "Europe/Rome"), + ("ENCELADO_CONFIRM_LIVE", "CONFERMO LIVE")), Now); + + BotConfig file = Saved(); + Assert.Equal("EUR", file.Ui.DisplayCurrency); + Assert.Equal("warn", file.Logging.Level); + Assert.False(file.Run.Autostart); + Assert.Equal("4242", file.Notifications.Telegram.ChatId); + Assert.Contains("ENCELADO_DISPLAY_CURRENCY", o.Imported); + Assert.DoesNotContain("ENCELADO_LOG_LEVEL", o.Imported); + Assert.DoesNotContain("TZ", o.Imported); + Assert.DoesNotContain("ENCELADO_CONFIRM_LIVE", o.Imported); + Assert.Contains("ENCELADO_CONFIRM_LIVE", o.Ignored); + Assert.DoesNotContain("TZ", o.Ignored); + } + + [Fact] + public void ItRunsOnceAndThenOnlyListsTheIgnoredVariables() + { + Func env = Env(("ENCELADO_DISPLAY_CURRENCY", "GBP"), ("ETORO_ENVIRONMENT", "demo")); + ImportOutcome first = EnvironmentImport.Run(ConfigPath, Store(), env, Now); + Assert.True(first.Ran); + Assert.Equal("GBP", Saved().Ui.DisplayCurrency); + + // The operator changes it in the interface; the variable is still on the container. + ConfigWriter.Apply(ConfigPath, new Dictionary { ["ui.displayCurrency"] = JsonValue.Create("USD") }); + ImportOutcome second = EnvironmentImport.Run(ConfigPath, Store(), env, Now.AddDays(1)); + + Assert.False(second.Ran); + Assert.False(second.ConfigChanged); + Assert.Equal("USD", Saved().Ui.DisplayCurrency); + Assert.Equal(["ETORO_ENVIRONMENT", "ENCELADO_DISPLAY_CURRENCY"], second.Ignored); + } + + [Fact] + public void TheKeyFileOfTheVersionBeforeIsImportedForBothAccountsAndRenamed() + { + string legacy = Path.Combine(_dir, KeyStores.FileName); + EncryptedFileKeyStore old = new(legacy, "passphrase-della-5.0"); + old.Save(demo: true, new EtoroKeys("api-demo-5.0", "user-demo-5.0", Now)); + old.Save(demo: false, new EtoroKeys("api-real-5.0", "user-real-5.0", Now)); + SecretStore store = Store(); + + ImportOutcome o = EnvironmentImport.Run(ConfigPath, store, Env((KeyStores.PassphraseVariable, "passphrase-della-5.0")), Now); + + Assert.Equal("api-demo-5.0", store.Etoro(demo: true)!.ApiKey); + Assert.Equal("api-real-5.0", store.Etoro(demo: false)!.ApiKey); + Assert.False(System.IO.File.Exists(legacy)); + Assert.True(System.IO.File.Exists(legacy + ".migrato")); + Assert.Contains(KeyStores.FileName, o.Imported); + Assert.Contains(KeyStores.PassphraseVariable, o.Ignored); + } + + [Fact] + public void WithoutThePassphraseTheOldKeyFileStaysAndTheNoteSaysSo() + { + string legacy = Path.Combine(_dir, KeyStores.FileName); + new EncryptedFileKeyStore(legacy, "passphrase").Save(demo: true, new EtoroKeys("a", "u", Now)); + + ImportOutcome o = EnvironmentImport.Run(ConfigPath, Store(), Env(), Now); + + Assert.True(System.IO.File.Exists(legacy)); + Assert.Contains(o.Notes, static n => n.Contains("reinserisci", StringComparison.Ordinal)); + } + + [Fact] + public void ALockedStoreDefersTheImportOfTheSecrets() + { + Store("prima").SaveTelegramToken("t"); + SecretStore locked = Store("dopo"); + + ImportOutcome o = EnvironmentImport.Run(ConfigPath, locked, Env(("ETORO_API_KEY", "a"), ("ETORO_USER_KEY", "u"), ("ENCELADO_DISPLAY_CURRENCY", "CHF")), Now); + + Assert.True(o.Deferred); + Assert.False(System.IO.File.Exists(Marker)); + Assert.Equal("CHF", Saved().Ui.DisplayCurrency); + Assert.Contains(o.Notes, static n => n.Contains("rimandata", StringComparison.Ordinal)); + } + + [Fact] + public void SecretsWrittenInTheFileMoveToTheStoreAndLeaveTheFile() + { + ConfigWriter.Apply(ConfigPath, new Dictionary + { + ["etoro.apiKey"] = JsonValue.Create("api-file"), + ["etoro.userKey"] = JsonValue.Create("user-file"), + ["notifications.telegram.botToken"] = JsonValue.Create("token-file"), + ["etoro.environment"] = JsonValue.Create("demo"), + }); + SecretStore store = Store(); + + EnvironmentImport.Run(ConfigPath, store, Env(), Now); + + Assert.Equal("api-file", store.Etoro(demo: true)!.ApiKey); + Assert.Equal("token-file", store.TelegramToken); + string text = System.IO.File.ReadAllText(ConfigPath); + Assert.DoesNotContain("api-file", text, StringComparison.Ordinal); + Assert.DoesNotContain("token-file", text, StringComparison.Ordinal); + Assert.DoesNotContain("\"environment\"", text, StringComparison.Ordinal); + } +} diff --git a/Encelado/tests/Encelado.Tests/HotApplyTests.cs b/Encelado/tests/Encelado.Tests/HotApplyTests.cs new file mode 100644 index 0000000..9b0554d --- /dev/null +++ b/Encelado/tests/Encelado.Tests/HotApplyTests.cs @@ -0,0 +1,358 @@ +using System.Net; +using System.Net.Http; +using System.Text; +using Encelado.Core.Baskets; +using Encelado.Core.Baskets.Data; +using Encelado.Core.Broker; +using Encelado.Core.Notifications; +using Encelado.Engine.Configuration; +using Encelado.Engine.Logging; +using Encelado.Engine.Settings; +using Encelado.Server.Web; + +namespace Encelado.Tests; + +/// The strategy changes in place under a running engine (decisions C10, C11). +public class StrategyHotApplyTests +{ + private static BasketStrategyConfig Default() => BasketStrategyConfig.ParseText(BasketStrategyConfig.DefaultJson, out _); + + [Fact] + public void CopyFromTakesEveryValueAndKeepsTheSectionsAndTheBasketsInPlace() + { + BasketStrategyConfig live = Default(); + RiskOptions risk = live.Risk; + BasketDefinition first = live.Baskets[0]; + BasketStrategyConfig fresh = Default(); + fresh.Preset = PresetName.Aggressive; + fresh.Window = 150; + fresh.Risk.MaxMarginUsePct = 33; + fresh.Learning.Enabled = true; + fresh.Sessions = [(7, 16)]; + fresh.Baskets[0].Enabled = false; + fresh.ZStopOverride = 4.2; + + live.CopyFrom(fresh); + + Assert.Equal(PresetName.Aggressive, live.Preset); + Assert.Equal(150, live.Window); + Assert.Same(risk, live.Risk); + Assert.Equal(33, live.Risk.MaxMarginUsePct); + Assert.True(live.Learning.Enabled); + Assert.Equal([(7, 16)], live.Sessions); + Assert.Same(first, live.Baskets[0]); + Assert.False(first.Enabled); + Assert.Equal(4.2, live.Effective().ZStop); + Assert.Equal(fresh.Canonical(), live.Canonical()); + } + + [Fact] + public void ThePairsAndTheDirectCrossesAreTheStructure() + { + BasketStrategyConfig a = Default(); + BasketStrategyConfig b = Default(); + b.Preset = PresetName.Conservative; + b.Baskets[3].Enabled = false; + Assert.True(a.SameStructure(b)); + + b.PreferDirectCross = true; + Assert.False(a.SameStructure(b)); + + BasketStrategyConfig c = Default(); + c.Baskets[1].B = "USDJPY"; + Assert.False(a.SameStructure(c)); + } + + [Fact] + public void ReloadMakesTheDeciderTakeTheNewPresetAndTheHashFollows() + { + BasketStrategyConfig cfg = Default(); + BasketDecider decider = new(cfg); + string before = cfg.Hash(); + Assert.Equal(PresetName.Moderate, decider.Preset.Name); + + BasketStrategyConfig fresh = Default(); + fresh.Preset = PresetName.Aggressive; + cfg.CopyFrom(fresh); + Assert.Equal(PresetName.Moderate, decider.Preset.Name); + + decider.Reload(); + Assert.Equal(PresetName.Aggressive, decider.Preset.Name); + Assert.Equal(BasketPresets.Aggressive.ZIn, decider.Preset.ZIn); + Assert.NotEqual(before, cfg.Hash()); + } +} + +/// An open basket keeps what it entered with; a basket switched off keeps its exits. +public class OpenBasketRulesTests +{ + private static readonly 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, ""); + private static readonly 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, ""); + + /// Quiet series, then a jump of leg A that takes |z| far beyond 3.5 (the fixture of the recovery tests). + private static BasketContext JumpContext(BasketPosition p) + { + SymbolSeries a = new(EurUsd, TimeSpan.FromMinutes(15)); + SymbolSeries b = new(UsdChf, TimeSpan.FromMinutes(15)); + Random rng = new(42); + DateTime t0 = new(2026, 9, 21, 0, 0, 0, DateTimeKind.Utc); + double pa = 1.10, pb = 0.90; + for (int i = 0; i < 130; i++) + { + double na = (rng.NextDouble() - 0.5) * 0.0004; + pa += na; + pb -= na * 0.8 + (rng.NextDouble() - 0.5) * 0.0001; + if (i == 129) + { + pa *= 1.02; + } + + DateTime t = t0.AddMinutes(15 * i); + a.Append(new BidAskBar(t, pa - 0.00005, pa + 0.0001, pa - 0.0002, pa - 0.00005, pa + 0.00005, pa + 0.0002, pa - 0.0001, pa + 0.00005, 0.0001, 20, "test")); + b.Append(new BidAskBar(t, pb - 0.00005, pb + 0.0001, pb - 0.0002, pb - 0.00005, pb + 0.00005, pb + 0.0002, pb - 0.0001, pb + 0.00005, 0.0001, 20, "test")); + } + + DateTime now = t0.AddMinutes(15 * 130); + a.OnQuote(new QuoteSnapshot(1, now, pa - 0.00005, pa + 0.00005, true), now); + b.OnQuote(new QuoteSnapshot(6, now, pb - 0.00005, pb + 0.00005, true), now); + return new BasketContext + { + TimeUtc = now, + BasketId = "EURUSD/USDCHF", + Name = "EURUSD/USDCHF", + Cross = SyntheticCross.Derive("EURUSD", "USDCHF"), + A = a, + B = b, + Equity = 10_000, + IsBarClose = true, + PipValueUsdA = 0.0001, + PipValueUsdB = 0.0001 / 0.9, + UsdPerQuoteA = 1, + UsdPerQuoteB = 1 / 0.9, + Mid = s => s == "EURUSD" ? a.Mid : s == "USDCHF" ? b.Mid : null, + Position = p, + }; + } + + private static BasketPosition SoldCross(double zStop) => new() + { + BasketId = "B1", + Name = "EURUSD/USDCHF", + BuyCross = false, + A = new BasketLeg { Symbol = "EURUSD", InstrumentId = 1, IsBuy = false, Units = 10_000, EntryPrice = 1.10, PositionId = 1, OpenedUtc = DateTime.UtcNow.AddHours(-3) }, + B = new BasketLeg { Symbol = "USDCHF", InstrumentId = 6, IsBuy = false, Units = 9_000, EntryPrice = 0.90, PositionId = 2, OpenedUtc = DateTime.UtcNow.AddHours(-3) }, + OpenedUtc = DateTime.UtcNow.AddHours(-3), + EntryZ = 2.1, + LastAddZ = 2.1, + BarsHeld = 12, + TpPips = 10, + MaxLossUsd = 1_000_000, + ZStop = zStop, + MaxAdds = 0, + EquityAtEntry = 10_000, + }; + + /// A basket saved before 5.1 has no stop of its own: the preset in force decides, as before. + [Fact] + public void ABasketWithoutItsOwnStopFollowsThePreset() + { + BasketDecision d = new BasketDecider(BasketStrategyConfig.ParseText(BasketStrategyConfig.DefaultJson, out _)).Evaluate(JumpContext(SoldCross(double.NaN))); + + Assert.Equal(DecisionKind.Exit, d.Kind); + Assert.Contains("stop_z", d.ReasonCodes); + } + + /// The stop is the one the basket entered with: a preset changed since then does not move it. + [Fact] + public void AnOpenBasketKeepsTheStopItEnteredWith() + { + BasketDecision d = new BasketDecider(BasketStrategyConfig.ParseText(BasketStrategyConfig.DefaultJson, out _)).Evaluate(JumpContext(SoldCross(50))); + + Assert.DoesNotContain("stop_z", d.ReasonCodes); + } + + [Fact] + public void ADisabledBasketStillExitsButNeverEntersOrAdds() + { + BasketDecision d = new BasketDecider(BasketStrategyConfig.ParseText(BasketStrategyConfig.DefaultJson, out _)).Evaluate(JumpContext(SoldCross(3.5))); + + Assert.Equal(DecisionKind.Exit, d.Kind); + Assert.True(BasketSlotPolicy.Evaluates(enabled: false, hasPosition: true)); + Assert.True(BasketSlotPolicy.MayExecute(enabled: false, d.Kind)); + Assert.False(BasketSlotPolicy.Evaluates(enabled: false, hasPosition: false)); + Assert.False(BasketSlotPolicy.MayExecute(enabled: false, DecisionKind.Enter)); + Assert.False(BasketSlotPolicy.MayExecute(enabled: false, DecisionKind.Add)); + Assert.True(BasketSlotPolicy.MayExecute(enabled: true, DecisionKind.Add)); + } + + [Fact] + public void ThePendingPlanCarriesTheEntryStopThroughARestart() + { + PendingEntry plan = new() + { + BasketId = "B1", BuyCross = true, EntryZ = -2.1, UnitsA = 1000, UnitsB = 900, TpPips = 10, MaxLossUsd = 150, + ZStop = 3.5, MaxAdds = 1, EquityAtEntry = 10_000, DecidedUtc = new DateTime(2026, 9, 30, 8, 0, 0, DateTimeKind.Utc), + }; + using MemoryStream ms = new(); + using (System.Text.Json.Utf8JsonWriter w = new(ms)) + { + w.WriteStartObject(); + plan.Write(w); + w.WriteEndObject(); + } + + using System.Text.Json.JsonDocument doc = System.Text.Json.JsonDocument.Parse(ms.ToArray()); + PendingEntry back = PendingEntry.Read(doc.RootElement.GetProperty("pending")); + Assert.Equal(3.5, back.ZStop); + Assert.Equal(1, back.MaxAdds); + } +} + +/// What the process applies at once after a save: the log, its window, the notifier. +public class ProcessReconfigureTests +{ + [Fact] + public void TheLogTakesANewLevelAndRotationAtOnce() + { + LogLevel before = Log.Minimum; + long bytes = Log.MaxBytes; + int files = Log.MaxFiles; + try + { + Log.Reconfigure(new LoggingOptions { Level = "error", MaxFileSizeMb = 5, MaxFiles = 3 }); + + Assert.Equal(LogLevel.Error, Log.Minimum); + Assert.False(Log.IsEnabled(LogLevel.Warn)); + Assert.Equal(5L * 1024 * 1024, Log.MaxBytes); + Assert.Equal(3, Log.MaxFiles); + } + finally + { + Log.Reconfigure(new LoggingOptions { Level = before.ToString(), MaxFileSizeMb = (int)(bytes / 1024 / 1024), MaxFiles = files }); + } + } + + [Fact] + public void TheLogWindowShrinksAndGrows() + { + LogBuffer buffer = new(1000); + for (int i = 0; i < 300; i++) + { + buffer.Add(new Encelado.Engine.EventRow("10:00:00", "info", $"riga {i}")); + } + + buffer.Resize(150); + Assert.Equal(150, buffer.Count); + Assert.Equal("riga 299", buffer.Read("tutti", null, 1).Rows[^1].Message); + Assert.Equal("riga 150", buffer.Read("tutti", null, 1000).Rows[0].Message); + + buffer.Resize(10); + Assert.Equal(100, buffer.Capacity); + Assert.Equal(100, buffer.Count); + } +} + +/// The notifier hub swaps the channel under the engine (decision C11). +public class NotifierHubTests +{ + /// getUpdates waits like Telegram's long polling (until cancelled); sendMessage answers ok. + private sealed class LongPollingTelegram : HttpMessageHandler + { + public int Polls; + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + if (request.RequestUri!.AbsolutePath.EndsWith("/getUpdates", StringComparison.Ordinal)) + { + Interlocked.Increment(ref Polls); + await Task.Delay(Timeout.Infinite, cancellationToken); + } + + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("""{"ok":true,"result":{"message_id":1}}""", Encoding.UTF8, "application/json") }; + } + } + + private static TelegramNotifier Channel(TelegramOptions o) => new(o, new LongPollingTelegram()) { MinInterval = TimeSpan.Zero, RetryDelays = [] }; + + [Fact] + public async Task TheChannelFollowsTheSettingsAndTheToken() + { + TelegramOptions shared = new() { Enabled = false, ChatId = "111", Commands = true }; + string token = string.Empty; + await using NotifierHub hub = new(shared, () => token, null, Channel); + + await hub.ReconfigureAsync(); + Assert.False(hub.IsActive); + Assert.Null(hub.Telegram); + + // Switched on without a token: still nothing, and the status says why. + shared.Enabled = true; + await hub.ReconfigureAsync(); + Assert.False(hub.IsActive); + Assert.Contains("token", hub.Status, StringComparison.Ordinal); + + token = "t0k3n"; + await hub.ReconfigureAsync(); + Assert.True(hub.IsActive); + TelegramNotifier first = hub.Telegram!; + Assert.True(first.CommandsRunning); + (bool ok, _) = await hub.SendTestAsync(CancellationToken.None); + Assert.True(ok); + + // Commands off: the poller stops, the channel stays. + shared.Commands = false; + await hub.ReconfigureAsync(); + Assert.Same(first, hub.Telegram); + Assert.False(first.CommandsRunning); + + // A new token is a new bot: a new channel. + token = "altro-t0k3n"; + await hub.ReconfigureAsync(); + Assert.NotSame(first, hub.Telegram); + Assert.True(hub.IsActive); + + shared.Enabled = false; + await hub.ReconfigureAsync(); + Assert.False(hub.IsActive); + Assert.Null(hub.Telegram); + (bool offOk, string offMessage) = await hub.SendTestAsync(CancellationToken.None); + Assert.False(offOk); + Assert.Contains("spento", offMessage, StringComparison.Ordinal); + } + + [Fact] + public void TheNullChannelIsNotActive() + { + Assert.False(NullNotifier.Instance.IsActive); + Assert.True(new TelegramOptions { Enabled = true, BotToken = "t", ChatId = "1" }.IsUsable); + } +} + +/// When the engine starts with the process (decisions C7, C9). +public class AutostartTests +{ + private static BotConfig Config(string mode, bool autostart) + { + BotConfig c = ConfigDefaults.Parse(); + c.Run.ExecutionMode = mode; + c.Run.AllowLive = true; + c.Run.Autostart = autostart; + return c; + } + + [Fact] + public void DemoStartsByItselfUnlessTurnedOff() + { + Assert.Equal(AutostartDecision.Start, AutostartPolicy.Decide(false, false, Config("Demo", true))); + Assert.Equal(AutostartDecision.Disabled, AutostartPolicy.Decide(false, false, Config("Demo", false))); + Assert.Equal(AutostartDecision.NoAutostartFlag, AutostartPolicy.Decide(true, false, Config("Demo", true))); + Assert.Equal(AutostartDecision.Sample, AutostartPolicy.Decide(false, true, Config("Demo", true))); + } + + [Fact] + public void LiveNeverStartsByItself() + { + Assert.Equal(AutostartDecision.LiveWaits, AutostartPolicy.Decide(false, false, Config("Live", true))); + Assert.Equal(AutostartDecision.Disabled, AutostartPolicy.Decide(false, false, Config("Live", false))); + } +} diff --git a/Encelado/tests/Encelado.Tests/KeyStoreTests.cs b/Encelado/tests/Encelado.Tests/KeyStoreTests.cs deleted file mode 100644 index 9d251ba..0000000 --- a/Encelado/tests/Encelado.Tests/KeyStoreTests.cs +++ /dev/null @@ -1,150 +0,0 @@ -using Encelado.Engine.Configuration; - -namespace Encelado.Tests; - -/// The portable key store of the 5.0: an AES-GCM file under a passphrase, the environment first. -public sealed class KeyStoreTests : IDisposable -{ - private readonly string _dir = Path.Combine(Path.GetTempPath(), $"encelado-keys-{Guid.NewGuid():N}"); - - private string FilePath => Path.Combine(_dir, KeyStores.FileName); - - public void Dispose() - { - if (Directory.Exists(_dir)) - { - Directory.Delete(_dir, recursive: true); - } - } - - [Fact] - public void KeysRoundTripPerEnvironmentAndAreNotReadableOnDisk() - { - EncryptedFileKeyStore store = new(FilePath, "una passphrase lunga a sufficienza"); - Assert.False(store.Exists); - Assert.Null(store.Load(demo: true)); - - store.Save(demo: true, new EtoroKeys("api-demo", "user-demo-value", DateTime.UtcNow)); - store.Save(demo: false, new EtoroKeys("api-real", "user-real", DateTime.UtcNow)); - - Assert.True(store.Exists); - Assert.Equal("api-demo", store.Load(demo: true)!.ApiKey); - Assert.Equal("user-real", store.Load(demo: false)!.UserKey); - byte[] onDisk = File.ReadAllBytes(FilePath); - Assert.DoesNotContain("user-demo-value"u8.ToArray(), Windows(onDisk, 15)); - Assert.Equal("ENC1"u8.ToArray(), onDisk[..4]); - - Assert.True(store.Clear(demo: true)); - Assert.Null(store.Load(demo: true)); - Assert.NotNull(store.Load(demo: false)); - Assert.True(store.Clear(demo: false)); - Assert.False(store.Exists); - Assert.False(store.Clear(demo: false)); - - static IEnumerable Windows(byte[] data, int size) - { - for (int i = 0; i + size <= data.Length; i++) - { - yield return data[i..(i + size)]; - } - } - } - - [Fact] - public void AWrongPassphraseOrACorruptFileReadsAsNoKeys() - { - EncryptedFileKeyStore store = new(FilePath, "giusta-giusta-giusta"); - store.Save(demo: true, new EtoroKeys("api", "user", DateTime.UtcNow)); - - Assert.Null(new EncryptedFileKeyStore(FilePath, "sbagliata-sbagliata").Load(demo: true)); - Assert.Null(new EncryptedFileKeyStore(FilePath, string.Empty).Load(demo: true)); - - File.WriteAllBytes(FilePath, [0x00, 0x01, 0x02, 0x03, 0x04]); - Assert.Null(store.Load(demo: true)); - - store.Save(demo: true, new EtoroKeys("new-api", "new-user", DateTime.UtcNow)); - Assert.Equal("new-api", store.Load(demo: true)!.ApiKey); - } - - [Fact] - public void WithoutAPassphraseTheFileStoreCannotSave() - { - EncryptedFileKeyStore store = new(FilePath, string.Empty); - Assert.False(store.CanSave); - Assert.Throws(() => store.Save(true, new EtoroKeys("a", "b", DateTime.UtcNow))); - } - - [Fact] - public void ResolvePrefersTheEnvironmentThenTheEncryptedFile() - { - string? previous = Environment.GetEnvironmentVariable(KeyStores.PassphraseVariable); - try - { - Environment.SetEnvironmentVariable(KeyStores.PassphraseVariable, "passphrase-di-prova"); - BotConfig config = new(); - config.Run.BaseDirectory = _dir; - Assert.False(KeyStores.Resolve(config, out string origin)); - Assert.Contains("nessuna", origin, StringComparison.OrdinalIgnoreCase); - - KeyStores.File(config).Save(demo: true, new EtoroKeys("api-stored", "user-stored", DateTime.UtcNow)); - Assert.True(KeyStores.Resolve(config, out origin)); - Assert.Equal("api-stored", config.Etoro.ApiKey); - Assert.Contains("cifrato", origin, StringComparison.OrdinalIgnoreCase); - - BotConfig fromEnv = new(); - fromEnv.Run.BaseDirectory = _dir; - fromEnv.Etoro.ApiKey = "api-env"; - fromEnv.Etoro.UserKey = "user-env"; - Assert.True(KeyStores.Resolve(fromEnv, out origin)); - Assert.Equal("api-env", fromEnv.Etoro.ApiKey); - Assert.Contains("ambiente", origin, StringComparison.OrdinalIgnoreCase); - - Environment.SetEnvironmentVariable(KeyStores.PassphraseVariable, null); - BotConfig noPass = new(); - noPass.Run.BaseDirectory = _dir; - Assert.False(KeyStores.Resolve(noPass, out origin)); - Assert.Contains(KeyStores.PassphraseVariable, origin, StringComparison.Ordinal); - } - finally - { - Environment.SetEnvironmentVariable(KeyStores.PassphraseVariable, previous); - } - } - - [Theory] - [InlineData("PKABCDEFGH1234", "PKABCD********")] - [InlineData("PKAB", "****")] - [InlineData("ab", "**")] - [InlineData("", "(vuota)")] - [InlineData(null, "(vuota)")] - public void MaskKeepsOnlyThePrefix(string? input, string expected) => - Assert.Equal(expected, KeyStores.Mask(input)); - - [Theory] - [InlineData(" PKKEY123 ", "PKKEY123")] - [InlineData("PKKEY123", "PKKEY123")] - [InlineData("PK​KEY123", "PKKEY123")] - [InlineData("P\0K\0K\0E\0Y\0", "PKKEY")] - [InlineData("PKKEY123\r\n", "PKKEY123")] - public void CleanStripsInvisibleCharactersFromPastedKeys(string raw, string expected) => - Assert.Equal(expected, KeyStores.Clean(raw)); - - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData(" ")] - [InlineData("\r\n")] - public void CleanReturnsNullWhenNothingUsableRemains(string? raw) => - Assert.Null(KeyStores.Clean(raw)); - - [Fact] - public void MaskNeverEchoesAWholeSecret() - { - const string secret = "abcdefghijklmnopqrstuvwxyz0123456789"; - string masked = KeyStores.Mask(secret); - - Assert.DoesNotContain(secret, masked, StringComparison.Ordinal); - Assert.DoesNotContain(secret[4..], masked, StringComparison.Ordinal); - Assert.StartsWith("abcd", masked, StringComparison.Ordinal); - } -} diff --git a/Encelado/tests/Encelado.Tests/SecretStoreTests.cs b/Encelado/tests/Encelado.Tests/SecretStoreTests.cs new file mode 100644 index 0000000..b85019c --- /dev/null +++ b/Encelado/tests/Encelado.Tests/SecretStoreTests.cs @@ -0,0 +1,271 @@ +using System.Buffers.Binary; +using System.Text; +using Encelado.Engine.Configuration; + +namespace Encelado.Tests; + +/// +/// The secret store of 5.1 (decision C3): the eToro keys of both accounts and the Telegram +/// token, encrypted with the interface password (or a local key without one), locked when +/// the password changes, unlocked with the previous one, reset with a backup. +/// +public sealed class SecretStoreTests : IDisposable +{ + /// Few PBKDF2 iterations: the tests prove the format, not the cost (the file records its own count). + private const int Fast = 1_000; + + private readonly string _dir = Path.Combine(Path.GetTempPath(), $"encelado-secrets-{Guid.NewGuid():N}"); + + public SecretStoreTests() => Directory.CreateDirectory(_dir); + + public void Dispose() + { + if (Directory.Exists(_dir)) + { + Directory.Delete(_dir, recursive: true); + } + } + + private SecretStore Open(string password) => new(_dir, password, Fast); + + private string FilePath => Path.Combine(_dir, SecretStore.FileName); + + private string KeyPath => Path.Combine(_dir, SecretStore.LocalKeyFileName); + + [Fact] + public void AnEmptyFolderIsAnEmptyStore() + { + SecretStore store = Open("password-lunga"); + + Assert.Equal(SecretStoreState.Empty, store.State); + Assert.Equal("empty", store.StateName); + Assert.Null(store.Etoro(demo: true)); + Assert.Equal(string.Empty, store.TelegramToken); + Assert.False(store.DescribeEtoro(demo: false).Present); + } + + [Fact] + public void BothAccountsAndTheTokenRoundTripAndAreNotReadableOnDisk() + { + SecretStore store = Open("password-lunga"); + store.SaveEtoro(demo: true, new EtoroKeys("api-demo-1234567", "user-demo-segreta", DateTime.UtcNow)); + store.SaveEtoro(demo: false, new EtoroKeys("api-real-7654321", "user-real-segreta", DateTime.UtcNow)); + store.SaveTelegramToken("123456:token-segretissimo"); + + Assert.Equal(SecretStoreState.Open, store.State); + SecretStore again = Open("password-lunga"); + Assert.Equal(SecretStoreState.Open, again.State); + Assert.Equal("api-demo-1234567", again.Etoro(demo: true)!.ApiKey); + Assert.Equal("user-real-segreta", again.Etoro(demo: false)!.UserKey); + Assert.Equal("123456:token-segretissimo", again.TelegramToken); + Assert.True(again.DescribeTelegram().Present); + Assert.StartsWith("api-de", again.DescribeEtoro(demo: true).Masked, StringComparison.Ordinal); + Assert.DoesNotContain("1234567", again.DescribeEtoro(demo: true).Masked, StringComparison.Ordinal); + + byte[] onDisk = File.ReadAllBytes(FilePath); + Assert.Equal("ENC2"u8.ToArray(), onDisk[..4]); + Assert.Equal(1, onDisk[4]); + Assert.Equal(Fast, BinaryPrimitives.ReadInt32LittleEndian(onDisk.AsSpan(5, 4))); + string raw = Encoding.Latin1.GetString(onDisk); + Assert.DoesNotContain("segreta", raw, StringComparison.Ordinal); + Assert.DoesNotContain("segretissimo", raw, StringComparison.Ordinal); + Assert.False(File.Exists(KeyPath)); + } + + [Fact] + public void TheSaltIsKeptAcrossRewritesAndTheNonceIsFresh() + { + SecretStore store = Open("password-lunga"); + store.SaveTelegramToken("uno"); + byte[] first = File.ReadAllBytes(FilePath); + store.SaveTelegramToken("due"); + byte[] second = File.ReadAllBytes(FilePath); + + Assert.Equal(first.AsSpan(9, 16).ToArray(), second.AsSpan(9, 16).ToArray()); + Assert.NotEqual(first.AsSpan(25, 12).ToArray(), second.AsSpan(25, 12).ToArray()); + } + + [Fact] + public void AnotherPasswordLocksTheStoreAndNothingCanBeSaved() + { + Open("giusta-giusta").SaveEtoro(demo: true, new EtoroKeys("api", "user", DateTime.UtcNow)); + + SecretStore locked = Open("sbagliata-sbagliata"); + + Assert.Equal(SecretStoreState.Locked, locked.State); + Assert.Contains("password", locked.Problem, StringComparison.OrdinalIgnoreCase); + Assert.Null(locked.Etoro(demo: true)); + Assert.Throws(() => locked.SaveTelegramToken("x")); + + // Without any password a store encrypted with one is locked too. + Assert.Equal(SecretStoreState.Locked, Open(string.Empty).State); + } + + [Fact] + public void ADamagedFileIsLockedNotACrash() + { + File.WriteAllBytes(FilePath, [0x45, 0x4E, 0x43, 0x32, 0x01]); + + Assert.Equal(SecretStoreState.Locked, Open("password").State); + } + + [Fact] + public void WithoutAPasswordALocalKeyProtectsTheStoreAndMovesUnderThePasswordWhenOneAppears() + { + SecretStore local = Open(string.Empty); + local.SaveEtoro(demo: true, new EtoroKeys("api-locale", "user-locale", DateTime.UtcNow)); + + Assert.Equal(SecretStoreState.LocalKey, local.State); + Assert.Equal("localKey", local.StateName); + Assert.True(File.Exists(KeyPath)); + Assert.Equal(32, File.ReadAllBytes(KeyPath).Length); + Assert.Equal(2, File.ReadAllBytes(FilePath)[4]); + Assert.Equal("api-locale", Open(string.Empty).Etoro(demo: true)!.ApiKey); + + SecretStore migrated = Open("ora-una-password"); + + Assert.Equal(SecretStoreState.Open, migrated.State); + Assert.NotNull(migrated.OpenNote); + Assert.False(File.Exists(KeyPath)); + Assert.Equal(1, File.ReadAllBytes(FilePath)[4]); + Assert.Equal("api-locale", Open("ora-una-password").Etoro(demo: true)!.ApiKey); + } + + [Fact] + public void ALockedStoreOpensWithThePreviousPasswordAndMovesUnderTheNewOne() + { + Open("vecchia-password").SaveEtoro(demo: false, new EtoroKeys("api-reale", "user-reale", DateTime.UtcNow)); + SecretStore store = Open("nuova-password"); + Assert.Equal(SecretStoreState.Locked, store.State); + + Assert.False(store.Unlock("tentativo-errato", out string refused)); + Assert.Contains("precedente", refused, StringComparison.Ordinal); + Assert.Equal(SecretStoreState.Locked, store.State); + + Assert.True(store.Unlock("vecchia-password", out string message)); + Assert.Contains("sbloccati", message, StringComparison.Ordinal); + Assert.Equal(SecretStoreState.Open, store.State); + Assert.Equal("api-reale", store.Etoro(demo: false)!.ApiKey); + Assert.Equal(SecretStoreState.Open, Open("nuova-password").State); + Assert.Equal(SecretStoreState.Locked, Open("vecchia-password").State); + } + + [Fact] + public void AResetStartsEmptyAndKeepsTheOldFileAsABackup() + { + Open("prima").SaveTelegramToken("token-vecchio"); + SecretStore store = Open("dopo"); + Assert.Equal(SecretStoreState.Locked, store.State); + + string? backup = store.Reset(); + + Assert.NotNull(backup); + Assert.True(File.Exists(backup)); + Assert.EndsWith(".bak", backup, StringComparison.Ordinal); + Assert.False(File.Exists(FilePath)); + Assert.Equal(SecretStoreState.Empty, store.State); + + store.SaveTelegramToken("token-nuovo"); + Assert.Equal(SecretStoreState.Open, store.State); + Assert.Equal("token-nuovo", Open("dopo").TelegramToken); + } + + [Fact] + public void KeysAndTokenCanBeRemoved() + { + SecretStore store = Open("password"); + store.SaveEtoro(demo: true, new EtoroKeys("a", "b", DateTime.UtcNow)); + store.SaveTelegramToken("t"); + + Assert.True(store.ClearEtoro(demo: true)); + Assert.False(store.ClearEtoro(demo: true)); + Assert.True(store.ClearTelegramToken()); + Assert.False(store.ClearTelegramToken()); + Assert.Null(Open("password").Etoro(demo: true)); + Assert.Equal(string.Empty, Open("password").TelegramToken); + } + + [Theory] + [InlineData("PKABCDEFGH1234", "PKABCD********")] + [InlineData("PKAB", "****")] + [InlineData("ab", "**")] + [InlineData("", "(vuota)")] + [InlineData(null, "(vuota)")] + public void MaskKeepsOnlyThePrefix(string? input, string expected) => + Assert.Equal(expected, KeyStores.Mask(input)); + + [Theory] + [InlineData(" PKKEY123 ", "PKKEY123")] + [InlineData("PKKEY123", "PKKEY123")] + [InlineData("PK​KEY123", "PKKEY123")] + [InlineData("P\0K\0K\0E\0Y\0", "PKKEY")] + [InlineData("PKKEY123\r\n", "PKKEY123")] + public void CleanStripsInvisibleCharactersFromPastedKeys(string raw, string expected) => + Assert.Equal(expected, KeyStores.Clean(raw)); + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("\r\n")] + public void CleanReturnsNullWhenNothingUsableRemains(string? raw) => + Assert.Null(KeyStores.Clean(raw)); + + [Fact] + public void MaskNeverEchoesAWholeSecret() + { + const string secret = "abcdefghijklmnopqrstuvwxyz0123456789"; + string masked = KeyStores.Mask(secret); + + Assert.DoesNotContain(secret, masked, StringComparison.Ordinal); + Assert.DoesNotContain(secret[4..], masked, StringComparison.Ordinal); + Assert.StartsWith("abcd", masked, StringComparison.Ordinal); + } +} + +/// The interface password (decision C1): the new name wins, the 5.0 name still works with a warning. +public class InterfacePasswordTests +{ + private static Func Env(params (string Name, string Value)[] vars) => + name => vars.FirstOrDefault(v => v.Name == name).Value; + + [Fact] + public void ThePasswordVariableIsTheSource() + { + InterfacePassword p = InterfacePassword.Resolve(Env(("ENCELADO_PASSWORD", " segreta "))); + + Assert.Equal("segreta", p.Value); + Assert.Equal("ENCELADO_PASSWORD", p.Source); + Assert.Empty(p.Warnings); + Assert.True(p.IsSet); + } + + [Fact] + public void TheTokenOfTheVersionBeforeStillWorksWithAWarning() + { + InterfacePassword p = InterfacePassword.Resolve(Env(("ENCELADO_WEB_TOKEN", "vecchio"))); + + Assert.Equal("vecchio", p.Value); + Assert.Equal("ENCELADO_WEB_TOKEN", p.Source); + Assert.Contains(p.Warnings, static w => w.Contains("deprecata", StringComparison.Ordinal)); + } + + [Fact] + public void WhenBothDifferThePasswordWins() + { + InterfacePassword p = InterfacePassword.Resolve(Env(("ENCELADO_PASSWORD", "nuova"), ("ENCELADO_WEB_TOKEN", "vecchio"))); + + Assert.Equal("nuova", p.Value); + Assert.Equal("ENCELADO_PASSWORD", p.Source); + Assert.Contains(p.Warnings, static w => w.Contains("diversa", StringComparison.Ordinal)); + } + + [Fact] + public void WithoutEitherThereIsNoPassword() + { + InterfacePassword p = InterfacePassword.Resolve(Env(("ENCELADO_PASSWORD", " "))); + + Assert.False(p.IsSet); + Assert.Equal("none", p.Source); + } +} diff --git a/Encelado/tests/Encelado.Tests/SettingsRuntimeTests.cs b/Encelado/tests/Encelado.Tests/SettingsRuntimeTests.cs new file mode 100644 index 0000000..adfd2e9 --- /dev/null +++ b/Encelado/tests/Encelado.Tests/SettingsRuntimeTests.cs @@ -0,0 +1,468 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using Encelado.Core.Baskets; +using Encelado.Engine; +using Encelado.Engine.Configuration; +using Encelado.Engine.Settings; +using Encelado.Etoro; + +namespace Encelado.Tests; + +/// +/// Every save is applied by the running bot without a restart when possible (decision C11), +/// through the supervisor's factory seam with a fake engine: hot paths reach the engine as +/// a command, restart paths stop it without closing a basket and start it again, Live asks +/// for the phrase before anything is written, the account switch waits for a flat account. +/// +public sealed class SettingsRuntimeTests : IAsyncLifetime +{ + private const string Password = "password-di-prova"; + + private readonly string _dir = Path.Combine(Path.GetTempPath(), $"encelado-runtime-{Guid.NewGuid():N}"); + private readonly List _engines = []; + private BotSupervisor? _supervisor; + private SettingsRuntime? _runtime; + private int _processReconfigured; + private int _notifierReconfigured; + private int _historyInvalidated; + + private sealed class FakeEngine(bool liveConfirmed, ExecutionMode mode) : IEngine + { + public bool LiveConfirmed { get; } = liveConfirmed; + + public ExecutionMode Mode { get; } = mode; + + public List Commands { get; } = []; + + public bool ClosedAll { get; private set; } + + public int OpenBaskets { get; set; } + + public Func? Answer { get; set; } + + public Task RunAsync(CancellationToken ct) => Task.Delay(Timeout.Infinite, ct); + + public Task CloseAllAsync(string reason, CancellationToken ct) + { + ClosedAll = true; + return Task.CompletedTask; + } + + public Task ExecuteAsync(EngineCommand command, CancellationToken ct) + { + lock (Commands) + { + Commands.Add(command); + } + + return Task.FromResult(Answer?.Invoke(command) ?? new CommandResult(true, "applicato")); + } + + public BotSnapshot Snapshot(BotState state, string? error, DateTime? startedUtc, EventRow[] events) => + SampleSnapshot.Minimal(state) with { OpenBaskets = OpenBaskets, Account = Mode.Account() }; + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + + private string ConfigPath => Path.Combine(_dir, "encelado.json"); + + private string StrategyPath => Path.Combine(_dir, "strategy.json"); + + private SettingsRuntime Runtime => _runtime!; + + private BotSupervisor Supervisor => _supervisor!; + + public Task InitializeAsync() + { + Directory.CreateDirectory(_dir); + File.WriteAllText(ConfigPath, ConfigDefaults.Json); + File.WriteAllText(StrategyPath, BasketStrategyConfig.DefaultJson); + return Task.CompletedTask; + } + + /// Builds the runtime on the files as they are; edits encelado.json first. + private void Build(Action? configure = null) + { + configure?.Invoke(ConfigPath); + BotConfig config = ConfigLoader.Load(ConfigPath, out _); + SecretStore secrets = new(_dir, Password, 1_000); + secrets.SaveEtoro(demo: true, new EtoroKeys("api-demo", "user-demo", DateTime.UtcNow)); + secrets.SaveEtoro(demo: false, new EtoroKeys("api-real", "user-real", DateTime.UtcNow)); + _supervisor = new BotSupervisor(config, (c, confirmed) => + { + FakeEngine e = new(confirmed, c.Run.Mode); + lock (_engines) + { + _engines.Add(e); + } + + return e; + }); + _runtime = new SettingsRuntime(config, ConfigPath, secrets, _supervisor, new SettingsHooks + { + ReconfigureProcess = _ => Interlocked.Increment(ref _processReconfigured), + ReconfigureNotifier = () => + { + Interlocked.Increment(ref _notifierReconfigured); + return Task.CompletedTask; + }, + InvalidateHistory = () => Interlocked.Increment(ref _historyInvalidated), + VerifyEtoroKeys = static (o, _) => o.ApiKey == "rifiutata" ? throw new InvalidOperationException("401 Unauthorized") : Task.FromResult($"utente prova ({o.Environment})"), + VerifyTelegramToken = static (t, _) => Task.FromResult("encelado_bot"), + }); + } + + private static void Set(string path, string key, JsonNode value) => + ConfigWriter.Apply(path, new Dictionary { [key] = value }); + + public async Task DisposeAsync() + { + if (_supervisor is not null) + { + await _supervisor.DisposeAsync(); + } + + try + { + Directory.Delete(_dir, recursive: true); + } + catch (IOException) + { + // Cleaned later with the temp folder. + } + } + + [Fact] + public async Task AnImmediateChangeIsInMemoryAtOnceAndEqualToTheFile() + { + Build(); + + SettingsResult r = await Runtime.ApplyAsync(new Dictionary { ["ui.displayCurrency"] = "EUR", ["logging.level"] = "debug", ["notifications.telegram.chatId"] = "4242" }, null, CancellationToken.None); + + Assert.True(r.Ok, r.Message); + Assert.Equal(200, r.HttpStatus); + Assert.All(r.Results, static p => Assert.Equal("immediate", p.Applied)); + Assert.Equal("EUR", Runtime.Config.Ui.DisplayCurrency); + Assert.Equal("debug", Runtime.Config.Logging.Level); + Assert.Equal("4242", Runtime.Config.Notifications.Telegram.ChatId); + Assert.Equal(1, _processReconfigured); + Assert.Equal(1, _notifierReconfigured); + + BotConfig file = ConfigLoader.Load(ConfigPath, out _); + Assert.Equal(file.Ui.DisplayCurrency, Runtime.Config.Ui.DisplayCurrency); + Assert.Equal(file.Logging.Level, Runtime.Config.Logging.Level); + Assert.Equal(file.Notifications.Telegram.ChatId, Runtime.Config.Notifications.Telegram.ChatId); + Assert.Equal(file.Run.PollSeconds, Runtime.Config.Run.PollSeconds); + } + + [Fact] + public async Task AStrategyChangeReachesTheRunningEngineOnItsThread() + { + Build(); + Assert.True((await Runtime.StartEngineAsync(null)).Ok); + long version = Runtime.Version; + + SettingsResult r = await Runtime.ApplyAsync(new Dictionary { ["strategy:preset"] = "Aggressive", ["run.pollSeconds"] = "5" }, null, CancellationToken.None); + + Assert.True(r.Ok, r.Message); + Assert.Equal(SettingsResult.RestartNone, r.Restart); + Assert.All(r.Results, static p => Assert.Equal("engine", p.Applied)); + FakeEngine engine = Assert.Single(_engines); + EngineCommand command = Assert.Single(engine.Commands); + Assert.Equal(EngineCommandKind.ApplySettings, command.Kind); + Assert.Contains("strategy:preset", command.Argument, StringComparison.Ordinal); + Assert.Equal(PresetName.Aggressive, BasketStrategyConfig.Load(StrategyPath, out _).Preset); + Assert.Equal(PresetName.Aggressive, Runtime.Strategy.Current().Preset); + Assert.Equal(5, Runtime.Config.Run.PollSeconds); + Assert.True(Runtime.Version > version); + } + + [Fact] + public async Task WhenStoppedAnEngineChangeIsStoredForTheNextStart() + { + Build(); + + SettingsResult r = await Runtime.ApplyAsync(new Dictionary { ["strategy:baskets[2].enabled"] = "false" }, null, CancellationToken.None); + + Assert.True(r.Ok, r.Message); + Assert.Equal("stored", Assert.Single(r.Results).Applied); + Assert.Empty(_engines); + Assert.False(BasketStrategyConfig.Load(StrategyPath, out _).Baskets[2].Enabled); + } + + [Fact] + public async Task ARestartChangeStopsWithoutClosingAndStartsAgainInDemo() + { + Build(static p => Set(p, "run.closeOnShutdown", true)); + Assert.True((await Runtime.StartEngineAsync(null)).Ok); + + SettingsResult r = await Runtime.ApplyAsync(new Dictionary { ["strategy:preferDirectCross"] = "true" }, null, CancellationToken.None); + + Assert.True(r.Ok, r.Message); + Assert.Equal(SettingsResult.RestartDone, r.Restart); + Assert.Equal("restart", Assert.Single(r.Results).Applied); + Assert.Equal(2, _engines.Count); + Assert.False(_engines[0].ClosedAll, "un riavvio automatico non chiude mai i basket, anche con closeOnShutdown"); + Assert.False(_engines[1].LiveConfirmed); + Assert.Equal(ExecutionMode.Demo, _engines[1].Mode); + Assert.Equal(BotState.Running, Supervisor.State); + } + + [Fact] + public async Task LiveNeverStartsWithoutThePhrase() + { + Build(static p => + { + Set(p, "run.allowLive", true); + Set(p, "run.executionMode", "Live"); + }); + + CommandResult refused = await Runtime.StartEngineAsync(null); + Assert.False(refused.Ok); + Assert.Equal(CommandResult.NeedsPhrase, refused.Code); + Assert.Empty(_engines); + Assert.True(Supervisor.Snapshot().LiveNeedsConfirmation); + + CommandResult started = await Runtime.StartEngineAsync("CONFERMO LIVE"); + Assert.True(started.Ok, started.Message); + Assert.True(Assert.Single(_engines).LiveConfirmed); + Assert.False(Supervisor.Snapshot().LiveNeedsConfirmation); + } + + [Fact] + public async Task ARestartOfALiveEngineAsksForThePhraseBeforeWritingAnything() + { + Build(static p => + { + Set(p, "run.allowLive", true); + Set(p, "run.executionMode", "Live"); + }); + Assert.True((await Runtime.StartEngineAsync("CONFERMO LIVE")).Ok); + string before = File.ReadAllText(StrategyPath); + + SettingsResult asked = await Runtime.ApplyAsync(new Dictionary { ["strategy:preferDirectCross"] = "true" }, null, CancellationToken.None); + + Assert.False(asked.Ok); + Assert.Equal(SettingsResult.RestartNeedsPhrase, asked.Restart); + Assert.Equal(409, asked.HttpStatus); + Assert.Equal(before, File.ReadAllText(StrategyPath)); + Assert.Single(_engines); + + SettingsResult confirmed = await Runtime.ApplyAsync(new Dictionary { ["strategy:preferDirectCross"] = "true" }, "CONFERMO LIVE", CancellationToken.None); + + Assert.True(confirmed.Ok, confirmed.Message); + Assert.Equal(SettingsResult.RestartDone, confirmed.Restart); + Assert.Equal(2, _engines.Count); + Assert.True(_engines[1].LiveConfirmed); + } + + [Fact] + public async Task AHotChangeOfALiveEngineNeedsNoPhrase() + { + Build(static p => + { + Set(p, "run.allowLive", true); + Set(p, "run.executionMode", "Live"); + }); + Assert.True((await Runtime.StartEngineAsync("CONFERMO LIVE")).Ok); + + SettingsResult r = await Runtime.ApplyAsync(new Dictionary { ["strategy:dailyLossPct"] = "2.5" }, null, CancellationToken.None); + + Assert.True(r.Ok, r.Message); + Assert.Equal("engine", Assert.Single(r.Results).Applied); + Assert.Single(_engines); + } + + [Fact] + public async Task TheAccountDoesNotChangeWhileBasketsAreOpen() + { + Build(); + Assert.True((await Runtime.StartEngineAsync(null)).Ok); + _engines[0].OpenBaskets = 1; + + SettingsResult r = await Runtime.ApplyAsync(new Dictionary { ["run.allowLive"] = "true", ["run.executionMode"] = "Live" }, "CONFERMO LIVE", CancellationToken.None); + + Assert.False(r.Ok); + Assert.Equal(SettingsResult.RestartRefused, r.Restart); + Assert.Equal(409, r.HttpStatus); + Assert.Contains("kill-switch", r.Message, StringComparison.Ordinal); + Assert.Equal(ExecutionMode.Demo, ConfigLoader.Load(ConfigPath, out _).Run.Mode); + Assert.Single(_engines); + } + + [Fact] + public async Task TheAccountDoesNotChangeWhenTheSavedStateHoldsBaskets() + { + Build(); + string state = Path.Combine(Runtime.Config.Run.DataPath, "state"); + Directory.CreateDirectory(state); + File.WriteAllText(Path.Combine(state, "baskets_state.json"), """{ "mode": "Demo", "baskets": [ { "name": "EURUSD/USDCHF" } ], "pendingEntries": [] }"""); + + SettingsResult r = await Runtime.ApplyAsync(new Dictionary { ["run.allowLive"] = "true", ["run.executionMode"] = "Live" }, null, CancellationToken.None); + + Assert.Equal(SettingsResult.RestartRefused, r.Restart); + Assert.Equal(ExecutionMode.Demo, ConfigLoader.Load(ConfigPath, out _).Run.Mode); + } + + [Fact] + public async Task SwitchingToLiveWithThePhraseRestartsOnTheRealAccount() + { + Build(); + Assert.True((await Runtime.StartEngineAsync(null)).Ok); + + SettingsResult asked = await Runtime.ApplyAsync(new Dictionary { ["run.allowLive"] = "true", ["run.executionMode"] = "Live" }, null, CancellationToken.None); + Assert.Equal(SettingsResult.RestartNeedsPhrase, asked.Restart); + Assert.Equal(ExecutionMode.Demo, ConfigLoader.Load(ConfigPath, out _).Run.Mode); + + SettingsResult r = await Runtime.ApplyAsync(new Dictionary { ["run.allowLive"] = "true", ["run.executionMode"] = "Live" }, "CONFERMO LIVE", CancellationToken.None); + + Assert.True(r.Ok, r.Message); + Assert.Equal(2, _engines.Count); + Assert.Equal(ExecutionMode.Live, _engines[1].Mode); + Assert.True(_engines[1].LiveConfirmed); + Assert.Equal("real", Runtime.Config.Etoro.Environment); + Assert.True(_historyInvalidated > 0); + } + + [Fact] + public async Task InvalidValuesAndCombinationsWriteNothing() + { + Build(); + string config = File.ReadAllText(ConfigPath); + string strategy = File.ReadAllText(StrategyPath); + + SettingsResult field = await Runtime.ApplyAsync(new Dictionary { ["run.pollSeconds"] = "99", ["nessuno.percorso"] = "1" }, null, CancellationToken.None); + Assert.False(field.Ok); + Assert.Equal(400, field.HttpStatus); + Assert.True(field.Errors.ContainsKey("run.pollSeconds")); + Assert.True(field.Errors.ContainsKey("nessuno.percorso")); + + // zStop must exceed zIn: each value is fine alone, the combination is not. + SettingsResult combination = await Runtime.ApplyAsync(new Dictionary { ["strategy:zStop"] = "1.5" }, null, CancellationToken.None); + Assert.False(combination.Ok); + Assert.Contains("zStop", combination.Message, StringComparison.Ordinal); + + SettingsResult live = await Runtime.ApplyAsync(new Dictionary { ["run.executionMode"] = "Live" }, "CONFERMO LIVE", CancellationToken.None); + Assert.False(live.Ok); + Assert.Contains("allowLive", live.Message, StringComparison.Ordinal); + + Assert.Equal(config, File.ReadAllText(ConfigPath)); + Assert.Equal(strategy, File.ReadAllText(StrategyPath)); + } + + [Fact] + public async Task AnOverrideLeftEmptyLeavesTheFile() + { + Build(); + Assert.True((await Runtime.ApplyAsync(new Dictionary { ["strategy:tpPips"] = "14" }, null, CancellationToken.None)).Ok); + Assert.Equal(14, BasketStrategyConfig.Load(StrategyPath, out _).Effective().TpPips); + + Assert.True((await Runtime.ApplyAsync(new Dictionary { ["strategy:tpPips"] = string.Empty }, null, CancellationToken.None)).Ok); + Assert.Null(JsonNode.Parse(File.ReadAllText(StrategyPath))!["tpPips"]); + Assert.Equal(BasketPresets.Moderate.TpPips, BasketStrategyConfig.Load(StrategyPath, out _).Effective().TpPips); + } + + [Fact] + public async Task TheKeysOfTheVersionBeforeLeaveTheFileAtTheNextSave() + { + Build(static p => + { + Set(p, "etoro.environment", "demo"); + Set(p, "run.paperSlippagePips", 0.3); + }); + + Assert.True((await Runtime.ApplyAsync(new Dictionary { ["ui.theme"] = "light" }, null, CancellationToken.None)).Ok); + + string text = File.ReadAllText(ConfigPath); + Assert.DoesNotContain("\"environment\"", text, StringComparison.Ordinal); + Assert.DoesNotContain("paperSlippagePips", text, StringComparison.Ordinal); + Assert.Contains("\"light\"", text, StringComparison.Ordinal); + } + + [Fact] + public async Task KeysAreProvedOnTheirOwnAccountAndTheActiveOnesRestartTheEngine() + { + Build(); + SecretActionResult refused = await Runtime.SaveKeysAsync("demo", "rifiutata", "user", null, CancellationToken.None); + Assert.False(refused.Ok); + Assert.Equal(400, refused.HttpStatus); + Assert.Equal("api-demo", Runtime.Secrets.Etoro(demo: true)!.ApiKey); + + SecretActionResult live = await Runtime.SaveKeysAsync("live", "api-real-nuova", "user-real-nuova", null, CancellationToken.None); + Assert.True(live.Ok, live.Message); + Assert.Contains("(real)", live.Detail, StringComparison.Ordinal); + Assert.Equal("api-real-nuova", Runtime.Secrets.Etoro(demo: false)!.ApiKey); + + Assert.True((await Runtime.StartEngineAsync(null)).Ok); + SecretActionResult active = await Runtime.SaveKeysAsync("demo", "api-demo-nuova", "user-demo-nuova", null, CancellationToken.None); + Assert.True(active.Ok, active.Message); + Assert.Equal(SettingsResult.RestartDone, active.Restart); + Assert.Equal(2, _engines.Count); + + SecretActionResult delete = await Runtime.DeleteKeysAsync("demo", CancellationToken.None); + Assert.False(delete.Ok); + Assert.Equal(409, delete.HttpStatus); + Assert.True((await Runtime.DeleteKeysAsync("live", CancellationToken.None)).Ok); + Assert.Null(Runtime.Secrets.Etoro(demo: false)); + } + + [Fact] + public async Task TheTelegramTokenIsProvedAndTheNotifierFollows() + { + Build(); + + SecretActionResult r = await Runtime.SaveTelegramTokenAsync(" 123:abc ", CancellationToken.None); + + Assert.True(r.Ok, r.Message); + Assert.Equal("123:abc", Runtime.Secrets.TelegramToken); + Assert.Equal(1, _notifierReconfigured); + Assert.True((await Runtime.DeleteTelegramTokenAsync(CancellationToken.None)).Ok); + Assert.Equal(string.Empty, Runtime.Secrets.TelegramToken); + Assert.Equal(2, _notifierReconfigured); + } + + [Fact] + public void TheDescriptionHasTheShapeOfTheApi() + { + Build(); + + using JsonDocument doc = JsonDocument.Parse(Runtime.Describe()); + JsonElement root = doc.RootElement; + + Assert.Equal("demo", root.GetProperty("engine").GetProperty("account").GetString()); + Assert.False(root.GetProperty("engine").GetProperty("running").GetBoolean()); + JsonElement strategia = root.GetProperty("groups").EnumerateArray().First(static g => g.GetProperty("key").GetString() == "strategia"); + Assert.Equal("strategy", strategia.GetProperty("target").GetString()); + JsonElement preset = strategia.GetProperty("fields").EnumerateArray().First(static f => f.GetProperty("path").GetString() == "strategy:preset"); + Assert.Equal("Moderate", preset.GetProperty("value").GetString()); + Assert.Equal("choice", preset.GetProperty("kind").GetString()); + Assert.Equal("engine", preset.GetProperty("scope").GetString()); + JsonElement poll = root.GetProperty("groups").EnumerateArray().SelectMany(static g => g.GetProperty("fields").EnumerateArray()).First(static f => f.GetProperty("path").GetString() == "run.pollSeconds"); + Assert.Equal(2, poll.GetProperty("min").GetDouble()); + Assert.Equal(30, poll.GetProperty("max").GetDouble()); + + JsonElement secrets = root.GetProperty("secrets"); + Assert.Equal("open", secrets.GetProperty("state").GetString()); + Assert.True(secrets.GetProperty("etoro").GetProperty("demo").GetProperty("present").GetBoolean()); + Assert.True(secrets.GetProperty("etoro").GetProperty("live").GetProperty("present").GetBoolean()); + Assert.False(secrets.GetProperty("telegram").GetProperty("present").GetBoolean()); + Assert.Equal(JsonValueKind.Null, secrets.GetProperty("telegram").GetProperty("savedUtc").ValueKind); + Assert.DoesNotContain("user-demo", Runtime.Describe(), StringComparison.Ordinal); + } + + [Fact] + public async Task TheRestoreWaitsForAStoppedEngine() + { + Build(static p => Set(p, "ui.theme", "light")); + Assert.True((await Runtime.StartEngineAsync(null)).Ok); + Assert.Equal(409, (await Runtime.RestoreAsync(CancellationToken.None)).HttpStatus); + + await Supervisor.StopAsync(); + SecretActionResult r = await Runtime.RestoreAsync(CancellationToken.None); + + Assert.True(r.Ok, r.Message); + Assert.True(File.Exists(r.Detail)); + Assert.Equal("dark", Runtime.Config.Ui.Theme); + Assert.Equal(ConfigDefaults.Json, File.ReadAllText(ConfigPath)); + } +} diff --git a/Encelado/tests/Encelado.Tests/WebTests.cs b/Encelado/tests/Encelado.Tests/WebTests.cs index 659a79f..2839679 100644 --- a/Encelado/tests/Encelado.Tests/WebTests.cs +++ b/Encelado/tests/Encelado.Tests/WebTests.cs @@ -106,10 +106,10 @@ public class EmbeddedUiTests } } -/// (bb) The web host on a real port: token, stream with one snapshot per second, history CSV. +/// (bb) The web host on a real port: password and session, stream with one snapshot per second, history CSV, settings. public sealed class WebHostTests : IAsyncLifetime { - private const string Token = "t0ken-di-prova"; + private const string Password = "t0ken-di-prova"; private readonly string _dir = Path.Combine(Path.GetTempPath(), "encelado-web-" + Guid.NewGuid().ToString("N")); private WebApplication? _app; private BotSupervisor? _supervisor; @@ -119,13 +119,14 @@ public sealed class WebHostTests : IAsyncLifetime public async Task InitializeAsync() { Directory.CreateDirectory(_dir); - BotConfig config = ConfigDefaults.Parse(); - config.Run.BaseDirectory = _dir; string configPath = Path.Combine(_dir, "encelado.json"); File.WriteAllText(configPath, ConfigDefaults.Json); + File.WriteAllText(Path.Combine(_dir, "strategy.json"), Encelado.Core.Baskets.BasketStrategyConfig.DefaultJson); + BotConfig config = ConfigLoader.Load(configPath, out _); _supervisor = new BotSupervisor(config); _history = new HistoryService(config); + SecretStore secrets = new(_dir, Password, 1_000); WebContext ctx = new() { Config = config, @@ -133,12 +134,13 @@ public sealed class WebHostTests : IAsyncLifetime Log = new LogBuffer(2000), History = _history, ConfigPath = configPath, + Settings = new Engine.Settings.SettingsRuntime(config, configPath, secrets, _supervisor), Sample = true, Start = static _ => Task.FromResult(new CommandResult(false, "non in questo test")), Learn = static () => Task.FromResult(new CommandResult(false, "non in questo test")), }; - _app = WebHost.Build(ctx, 0, Token, listenAll: false); + _app = WebHost.Build(ctx, 0, Password, listenAll: false); await _app.StartAsync(); string address = _app.Services.GetRequiredService().Features.Get()!.Addresses.First(); _client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false, UseCookies = false }) { BaseAddress = new Uri(address) }; @@ -176,12 +178,12 @@ public sealed class WebHostTests : IAsyncLifetime private HttpRequestMessage Authorised(HttpMethod method, string path) { HttpRequestMessage req = new(method, path); - req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Token); + req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Password); return req; } [Fact] - public async Task WithoutTheTokenTheApiSays401AndThePageRedirectsToLogin() + public async Task WithoutTheSessionTheApiSays401AndThePageRedirectsToLogin() { HttpResponseMessage api = await _client!.GetAsync("/api/snapshot"); Assert.Equal(HttpStatusCode.Unauthorized, api.StatusCode); @@ -192,23 +194,67 @@ public sealed class WebHostTests : IAsyncLifetime HttpResponseMessage health = await _client.GetAsync("/api/health"); Assert.Equal(HttpStatusCode.OK, health.StatusCode); + + // The files the login page needs are open; anything else is not. + Assert.True(WebHost.IsPublic("/css/app.css")); + Assert.True(WebHost.IsPublic("/img/flags.svg")); + Assert.False(WebHost.IsPublic("/api/settings")); } + /// + /// 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. + /// [Fact] - public async Task TheLoginSetsTheCookieAndTheBearerTokenOpensTheApi() + public async Task TheLoginSetsASessionCookieThatIsNotThePassword() { - using FormUrlEncodedContent form = new([new KeyValuePair("token", Token)]); + using FormUrlEncodedContent form = new([new KeyValuePair("password", Password)]); HttpResponseMessage login = await _client!.PostAsync("/login", form); Assert.Equal(HttpStatusCode.Redirect, login.StatusCode); string cookie = Assert.Single(login.Headers.GetValues("Set-Cookie")); Assert.StartsWith(WebHost.CookieName + "=", cookie, StringComparison.Ordinal); 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.DoesNotContain(Password, cookie, StringComparison.Ordinal); + Assert.NotEqual(WebHost.SessionValue("un'altra password"), value); - using FormUrlEncodedContent wrong = new([new KeyValuePair("token", "no")]); - HttpResponseMessage refused = await _client.PostAsync("/login", wrong); - Assert.NotEqual(HttpStatusCode.Redirect, refused.StatusCode); + HttpRequestMessage withCookie = new(HttpMethod.Get, "/api/snapshot"); + withCookie.Headers.Add("Cookie", $"{WebHost.CookieName}={value}"); + Assert.Equal(HttpStatusCode.OK, (await _client.SendAsync(withCookie)).StatusCode); - HttpResponseMessage snapshot = await _client.SendAsync(Authorised(HttpMethod.Get, "/api/snapshot")); + HttpRequestMessage rawPassword = new(HttpMethod.Get, "/api/snapshot"); + rawPassword.Headers.Add("Cookie", $"{WebHost.CookieName}={Password}"); + Assert.Equal(HttpStatusCode.Unauthorized, (await _client.SendAsync(rawPassword)).StatusCode); + + using FormUrlEncodedContent legacy = new([new KeyValuePair("token", Password)]); + Assert.Equal(HttpStatusCode.Redirect, (await _client.PostAsync("/login", legacy)).StatusCode); + + HttpResponseMessage logout = await _client.PostAsync("/logout", null); + Assert.Equal(HttpStatusCode.Redirect, logout.StatusCode); + Assert.Equal("/login", logout.Headers.Location?.ToString()); + Assert.Contains(logout.Headers.GetValues("Set-Cookie"), static c => c.StartsWith(WebHost.CookieName + "=;", StringComparison.Ordinal)); + } + + [Fact] + public async Task AWrongPasswordCostsASecondAndShowsTheLoginPageAgain() + { + using FormUrlEncodedContent wrong = new([new KeyValuePair("password", "no")]); + System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew(); + HttpResponseMessage refused = await _client!.PostAsync("/login", wrong); + sw.Stop(); + + Assert.Equal(HttpStatusCode.Unauthorized, refused.StatusCode); + Assert.True(sw.Elapsed >= TimeSpan.FromMilliseconds(900), $"risposta in {sw.Elapsed.TotalMilliseconds:F0} ms"); + Assert.Contains("Password errata", await refused.Content.ReadAsStringAsync(), StringComparison.Ordinal); + Assert.False(refused.Headers.Contains("Set-Cookie")); + } + + [Fact] + public async Task TheBearerPasswordOpensTheApiForScripts() + { + HttpResponseMessage snapshot = await _client!.SendAsync(Authorised(HttpMethod.Get, "/api/snapshot")); Assert.Equal(HttpStatusCode.OK, snapshot.StatusCode); using JsonDocument doc = JsonDocument.Parse(await snapshot.Content.ReadAsStringAsync()); Assert.Equal("running", doc.RootElement.GetProperty("state").GetString()); @@ -288,8 +334,59 @@ public sealed class WebHostTests : IAsyncLifetime HttpResponseMessage settings = await _client.SendAsync(Authorised(HttpMethod.Get, "/api/settings")); using JsonDocument s = JsonDocument.Parse(await settings.Content.ReadAsStringAsync()); Assert.Contains(s.RootElement.GetProperty("groups").EnumerateArray(), static g => g.GetProperty("fields").EnumerateArray().Any(static f => f.GetProperty("path").GetString() == "ui.displayCurrency")); + Assert.Contains(s.RootElement.GetProperty("groups").EnumerateArray(), static g => g.GetProperty("target").GetString() == "strategy" && g.GetProperty("fields").EnumerateArray().Any(static f => f.GetProperty("path").GetString() == "strategy:preset")); + JsonElement secrets = s.RootElement.GetProperty("secrets"); + Assert.Equal("empty", secrets.GetProperty("state").GetString()); + Assert.False(secrets.GetProperty("etoro").GetProperty("demo").GetProperty("present").GetBoolean()); + Assert.False(secrets.GetProperty("etoro").GetProperty("live").GetProperty("present").GetBoolean()); + Assert.Equal(JsonValueKind.Array, secrets.GetProperty("ignoredEnv").ValueKind); HttpResponseMessage unknown = await _client.SendAsync(Authorised(HttpMethod.Post, "/api/commands/nonesiste")); Assert.Equal(HttpStatusCode.BadRequest, unknown.StatusCode); } + + /// The preset is no longer a command (decision C10): it is chosen in the settings. + [Fact] + public async Task ThePresetIsNotACommandAnyMore() + { + HttpRequestMessage req = Authorised(HttpMethod.Post, "/api/commands/preset"); + req.Content = new StringContent("""{"argument":"Aggressive"}""", Encoding.UTF8, "application/json"); + HttpResponseMessage r = await _client!.SendAsync(req); + + Assert.Equal(HttpStatusCode.BadRequest, r.StatusCode); + using JsonDocument doc = JsonDocument.Parse(await r.Content.ReadAsStringAsync()); + Assert.False(doc.RootElement.GetProperty("ok").GetBoolean()); + } + + [Fact] + public async Task SettingsAreSavedWithTheNewShapeAndTheOldFlatObject() + { + HttpRequestMessage wrapped = Authorised(HttpMethod.Post, "/api/settings"); + wrapped.Content = new StringContent("""{"edits":{"ui.theme":"light","strategy:preset":"Conservative","strategy:sessions":["07-16","20-22"]}}""", Encoding.UTF8, "application/json"); + HttpResponseMessage r = await _client!.SendAsync(wrapped); + string body = await r.Content.ReadAsStringAsync(); + Assert.Equal(HttpStatusCode.OK, r.StatusCode); + using (JsonDocument doc = JsonDocument.Parse(body)) + { + Assert.True(doc.RootElement.GetProperty("ok").GetBoolean(), body); + Assert.Equal("none", doc.RootElement.GetProperty("restart").GetString()); + Assert.Equal(3, doc.RootElement.GetProperty("results").GetArrayLength()); + } + + HttpRequestMessage flat = Authorised(HttpMethod.Post, "/api/settings"); + flat.Content = new StringContent("""{"ui.displayCurrency":"EUR"}""", Encoding.UTF8, "application/json"); + Assert.Equal(HttpStatusCode.OK, (await _client.SendAsync(flat)).StatusCode); + + HttpRequestMessage invalid = Authorised(HttpMethod.Post, "/api/settings"); + invalid.Content = new StringContent("""{"edits":{"run.pollSeconds":"1"}}""", Encoding.UTF8, "application/json"); + HttpResponseMessage bad = await _client.SendAsync(invalid); + Assert.Equal(HttpStatusCode.BadRequest, bad.StatusCode); + using JsonDocument errors = JsonDocument.Parse(await bad.Content.ReadAsStringAsync()); + Assert.True(errors.RootElement.GetProperty("errors").TryGetProperty("run.pollSeconds", out _)); + + HttpResponseMessage page = await _client.SendAsync(Authorised(HttpMethod.Get, "/api/settings")); + string after = await page.Content.ReadAsStringAsync(); + Assert.Contains("\"value\":\"Conservative\"", after, StringComparison.Ordinal); + Assert.Contains("\"value\":\"07-16,20-22\"", after, StringComparison.Ordinal); + } }