`; 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 (``), messo al posto del segnaposto `` se la pagina lo contiene, altrimenti prima di ``.
+- `POST /logout` — cancella il cookie, **302** su `/login`.
+
+## Il flusso in tempo reale
+
+### `GET /api/stream` (Server-Sent Events)
+
+Un tick al secondo, `event: snapshot`, la stessa serializzazione condivisa da tutti i client (niente viene calcolato se nessuno è connesso). Il primo tick arriva subito; il server manda `retry: 3000`. Un client lento riceve solo il tick più recente.
+
+### `GET /api/snapshot`
+
+Lo stesso tick, una volta (per il polling senza `EventSource` e per gli screenshot con `?once=1`).
+
+### Il tick (v2)
+
+`nowUtc` è sempre il primo campo.
+
+```ts
+type Tick = {
+ nowUtc: string; // primo campo
+ v: 2;
+ frame: number; // contatore dei tick del server
+ state: "stopped" | "starting" | "running" | "stopping" | "faulted";
+ error: string; // vuoto se nessun errore
+ account: "demo" | "live"; // modalità: Demo = conto demo, Live = conto reale
+ preset: "Conservative" | "Moderate" | "Aggressive";
+ startedAtUtc: string | null;
+ uptimeSeconds: number;
+ engineTickAgeSeconds: number | null; // da quanto il ciclo di decisione non gira (null a motore fermo)
+ alarms: {
+ halted: boolean; // kill-switch o equity stop: entrate bloccate fino al reset
+ haltKind: "" | "kill" | "equity";
+ haltReason: string;
+ haltedWithResidue: boolean; // Halted-Residuo: posizioni del bot ancora sul conto
+ residueCount: number;
+ entriesBlockedReason: string; // vuoto se le entrate sono libere
+ entriesBlockedUntilUtc: string | null;
+ paused: boolean; // pausa dell'operatore (/pausa)
+ unreconciled: boolean;
+ unreconciledReason: string;
+ dailyLossHit: boolean;
+ recoveryPending: boolean;
+ secretsLocked: boolean; // segreti cifrati con un'altra password
+ liveNeedsConfirmation: boolean; // modalità Live, motore fermo: serve AVVIA con la frase
+ ignoredEnv: string[]; // variabili d'ambiente ignorate (da togliere dal container)
+ };
+ equity: number | null;
+ balance: number | null;
+ availableBalance: number | null;
+ usedMargin: number | null;
+ marginRatio: number | null; // equity / margine usato (null senza margine)
+ peakEquity: number | null; // al netto dei movimenti di cassa
+ drawdownPct: number | null; // 0..1
+ equityStopPct: number; // 0..1, dalla strategia
+ dailyLossPct: number; // 0..1, soglia dalla strategia
+ dailyLossUsedPct: number | null;// 0..1: quanto della soglia giornaliera è consumato
+ cumulativeCashFlow: number;
+ todayPnl: number | null; // realizzato netto (netProfit − fees) delle posizioni del bot chiuse oggi UTC, dallo storico eToro (+ stime provvisorie)
+ todayPnlPct: number | null; // todayPnl / equity netta di inizio giornata
+ todayPnlProvisional: boolean; // true se contiene stime non ancora confermate dallo storico
+ todayEquityChange: number | null; // equity netta ora − equity netta alle 00:00 UTC (realizzato + variazione dell'aperto, cassa esclusa)
+ dayStartEquity: number | null;
+ todayClosed: { baskets: number; won: number; lost: number; loneLegs: number };
+ openPnl: number | null; // P&L aperto dei basket del bot
+ accountOpenPnl: number | null; // P&L aperto di tutto il conto
+ openBaskets: number;
+ maxBaskets: number;
+ pendingBaskets: number;
+ pendingOrders: number;
+ orphanLegs: number;
+ foreignPositions: number;
+ displayCurrency: string; // USD, EUR, GBP, CHF, JPY, AUD, CAD, NZD
+ theme: "dark" | "light";
+ navExpanded: boolean;
+ fxRates: Record; // USD compreso (1)
+ baskets: TickBasket[];
+ quotes: Array<{ symbol: string; bid: number; ask: number; spreadPips: number; spreadMedianPips: number | null; ageSeconds: number | null }>;
+ health: {
+ api: "ok" | "degraded" | "error" | "off";
+ apiLatencyMs: number | null; // solo il viaggio HTTP, senza attese del limitatore
+ clockSkewSeconds: number | null;
+ quotaPeakPct: number | null; // 0..1: la classe di quota più usata
+ feeds: "ok" | "stale" | "error" | "off";
+ telegram: "ok" | "queue" | "error" | "off";
+ heartbeatAgeSeconds: number | null;
+ secrets: "open" | "empty" | "locked" | "localKey";
+ sseClients: number;
+ };
+ learning: {
+ mode: "ombra-disabilitato" | "ombra" | "attivo";
+ labelledRows: number;
+ target: number; // 300
+ rollingAuc: number | null;
+ banditPreset: string; // proposta, mai applicata
+ volModel: string; // "EWMA" | "HAR"
+ cycleRunning: boolean;
+ warnings: number;
+ };
+ nextEvent: { timeUtc: string; currency: string; title: string; impact: "High" | "Medium" | "Low" } | null;
+ events: Array<{ seq: number; timeUtc: string; level: "trace" | "debug" | "info" | "warn" | "error"; source: string; message: string }>;
+ // solo le righe di log nuove dall'ultimo tick (≤ 100), già su una riga; il client recupera il pregresso con /api/log
+ eventsSeq: number; // l'ultimo seq emesso finora
+ versions: { positions: number; market: number; learning: number; settings: number; system: number; history: number };
+ // un numero cambia quando la sezione cambia: il client rilegge l'endpoint solo allora
+};
+
+type TickBasket = {
+ name: string; // "EURUSD/USDCHF"
+ pairA: string; pairB: string;
+ cross: string; // cross sintetico, "EURCHF"
+ currencies: string[]; // valute coinvolte, es. ["EUR","USD","CHF"] (per le bandiere)
+ state: "Idle" | "Entering" | "PendingA" | "PendingB" | "Open" | "Adding" | "Exiting" | "Closed" | "Error" | "Disabled";
+ enabled: boolean;
+ isOpen: boolean;
+ side: "" | "buy" | "sell"; // verso del cross quando aperto
+ openLegs: number;
+ z: number | null; zIn: number | null; zOut: number | null; zStop: number | null;
+ rho: number | null; rhoShort: number | null; halfLife: number | null;
+ pips: number | null; tpPips: number; pnlUsd: number | null; costPips: number | null;
+ spreadRatioMax: number | null; // spread attuale / mediana 24 h, il peggiore delle due gambe
+ pMl: number | null; mlActive: boolean;
+ barsHeld: number; adds: number; entryZ: number | null;
+ minutesToEvent: number | null; nextEvent: string;
+ intent: string; // cosa farebbe il bot adesso, o perché non entra (italiano)
+ reasonCodes: string[];
+};
+```
+
+## Sezioni a richiesta
+
+Ogni sezione ha `asOfUtc`, un `ETag` e risponde **304** a `If-None-Match` uguale. Il client la rilegge quando cambia il numero corrispondente in `versions`, o ogni 30 s mentre la pagina è visibile.
+
+### `GET /api/positions`
+
+Le posizioni del conto, classificate a ogni riconciliazione (nessuna chiamata a eToro in più). A motore fermo le legge dallo storico/portafoglio (`source: "history"`) se ci sono le chiavi.
+
+```ts
+{ asOfUtc: string; source: "engine" | "history" | "none"; problem: string;
+ totals: { count: number; unrealizedPnl: number; margin: number; fees: number;
+ byOrigin: Record<"basket" | "orfana-bot" | "esterna", { count: number; unrealizedPnl: number; margin: number }> };
+ rows: Array<{ positionId: number; symbol: string; instrumentId: number; side: "long" | "short"; units: number;
+ openRate: number; currentRate: number | null; pips: number | null; openedUtc: string; minutesOpen: number;
+ stopLoss: number | null; takeProfit: number | null; leverage: number; margin: number; exposureUsd: number | null;
+ unrealizedPnl: number | null; fees: number; origin: "basket" | "orfana-bot" | "esterna";
+ basket: string; basketId: string; leg: "A" | "B" | "add" | ""; reason: string }>;
+ pendingOrders: Array<{ clientRef: string; orderId: number; basket: string; basketId: string; leg: string; symbol: string;
+ side: "buy" | "sell"; requestedUnits: number; sentUtc: string; ageSeconds: number; lastStatus: string; checks: number }> }
+```
+
+### `GET /api/market`
+
+```ts
+{ asOfUtc: string;
+ quotes: Array<{ symbol: string; bid: number; ask: number; mid: number; spreadPips: number; spreadMedian24hPips: number | null;
+ spreadRatio: number | null; quoteUtc: string; ageSeconds: number; realtime: boolean; atrPips: number | null;
+ usedBy: string[]; conversionOnly: boolean }>;
+ fx: Array<{ currency: string; usdPerUnit: number; sourcePair: string; inverted: boolean; timeUtc: string | null; ageSeconds: number | null }>;
+ calendar: { updatedUtc: string | null; state: string;
+ events: Array<{ timeUtc: string; currency: string; title: string; impact: "High" | "Medium" | "Low" | "Holiday";
+ forecast: string; previous: string; actual: string; affectsBaskets: string[]; blackout: boolean }> };
+ sentiment: Array<{ currency: string; net1h: number | null; net4h: number | null; net24h: number | null; hawkish4h: number | null; count24h: number }>;
+ riskOff4h: number | null;
+ news: { updatedUtc: string | null; state: string;
+ items: Array<{ publishedUtc: string; source: string; title: string; link: string; currencies: string[]; net: number; hawkish: number; riskOff: number }> };
+ volatility: Array<{ basket: string; model: "EWMA" | "HAR"; sigmaForecast: number | null; sigmaAverage30d: number | null; ratio: number | null; zInScale: number | null; bars: number }> }
+```
+
+Query facoltative: `calendarDays` (default 7), `impact` (default `High,Medium`), `news` (default 50).
+
+### `GET /api/baskets/detail?name=EURUSD/USDCHF`
+
+Il nome va nella query (`%2F` nel percorso non verrebbe decodificato).
+
+```ts
+{ asOfUtc: string; name: string; pairA: string; pairB: string; cross: string; signB: 1 | -1; enabled: boolean;
+ disabledReason: string; disabledUntilUtc: string | null; state: string; intent: string;
+ lastDecision: { kind: "Skip" | "Enter" | "Add" | "Exit" | "Hold"; reasonCodes: string[]; motivazione: string; atUtc: string } | null;
+ thresholds: { zIn: number; zInEffective: number | null; zOut: number; zStop: number; rhoMin: number; rhoShortMin: number;
+ halfLifeMin: number; halfLifeMax: number; tpPips: number; maxHoldingBars: number; costMultiple: number;
+ spreadMedianMultiple: number; spreadAnomalyMultiple: number; mlMinProbability: number };
+ eval: { z: number | null; dPips: number | null; rhoW: number | null; rhoShort: number | null; halfLife: number | null;
+ atrPipsA: number | null; atrPipsB: number | null; sigmaX: number | null; ewmaVolX: number | null; trendStrength: number | null;
+ priceA: number | null; priceB: number | null; spreadPipsA: number | null; spreadPipsB: number | null;
+ spreadMedianA: number | null; spreadMedianB: number | null; costPips: number | null; breakEvenWinRate: number | null;
+ cost: { passed: boolean; markupPipsA: number; markupPipsB: number; overnightPips: number; reason: string } | null } | null;
+ sizing: { unitsA: number; unitsB: number; notionalUsdA: number; notionalUsdB: number; lossAtStopUsd: number;
+ effectiveLeverage: number; marginUsd: number; bound: string } | null;
+ context: { minutesToNextHigh: number | null; minutesSinceLastHigh: number | null; surpriseLast: number | null;
+ netSentimentDiff1h: number | null; netSentimentDiff4h: number | null; netSentimentDiff24h: number | null;
+ hawkishDiff: number | null; riskOff: number | null; newsCount: number; nextEventLabel: string };
+ ml: { pMl: number | null; active: boolean; features: Array<{ name: string; label: string; value: number | null }> };
+ vol: { sigmaForecast: number | null; sigmaAverage30d: number | null; model: string };
+ position: null | { basketId: string; buyCross: boolean; openedUtc: string; minutesOpen: number; barsHeld: number; adds: number;
+ entryZ: number; lastAddZ: number | null; entryCostPips: number; tpPips: number; zStop: number; maxAdds: number;
+ pipsOpen: number | null; pnlOpenUsd: number | null; accruedFeesUsd: number; maxLossUsd: number;
+ stopDistanceUsd: number | null; zStopDistance: number | null; barsToTimeStop: number | null;
+ barsWithBrokenCorrelation: number; barsWithSpreadAnomaly: number; equityAtEntry: number; entryMotivazione: string;
+ legs: Array<{ leg: "A" | "B"; symbol: string; side: "buy" | "sell"; units: number; totalUnits: number; entryPrice: number;
+ bid: number | null; ask: number | null; pips: number | null; pnlUsd: number | null; entryFeesUsd: number;
+ nativeStopLoss: number | null; positionIds: number[];
+ venue: { unrealizedPnl: number | null; fees: number; currentRate: number | null; margin: number; leverage: number } | null }> };
+ pending: null | { leg: "A" | "B"; decidedUtc: string; ageSeconds: number; unitsA: number; unitsB: number; entryZ: number };
+ recent: Array<{ atUtc: string; evento: string; z: number | null; motivazione: string }> } // ultime 20 decisioni di chiusura barra
+```
+
+### `GET /api/system`
+
+Tutto ciò che non serve in dashboard: stato del motore, collegamento eToro, quote, feed, Telegram, processo, disco, log, informazioni.
+
+```ts
+{ asOfUtc: string;
+ engine: { state: string; account: "demo" | "live"; runId: string; strategyHash: string; preset: string;
+ startedUtc: string | null; uptimeSeconds: number; lastTickUtc: string | null; tickAgeSeconds: number | null;
+ heartbeatUtc: string | null; heartbeatAgeSeconds: number | null; recoveryPending: boolean; recoveryCause: string;
+ entriesBlockedReason: string; entriesBlockedUntilUtc: string | null; paused: boolean; autostart: boolean;
+ orphanPolicy: "Close" | "Report"; instanceLock: string };
+ api: { endpoint: string; account: "demo" | "live"; state: string; latencyMs: number | null; latencyAvg1mMs: number | null;
+ clockSkewSeconds: number | null; clockSkewMaxSeconds: number; consecutiveErrors: number;
+ lastError: { utc: string; message: string } | null;
+ quotas: Array<{ name: string; used: number; limit: number; windowSeconds: number; pausedUntilUtc: string | null; count429: number }> };
+ feeds: Array<{ name: string; kind: "calendar" | "rss"; currency: string; host: string; lastRequestUtc: string | null;
+ lastSuccessUtc: string | null; failures: number; backoffUntilUtc: string | null; robotsAllowed: boolean | null; lastError: string }>;
+ telegram: { configured: boolean; enabled: boolean; commands: boolean; hourlyStatus: boolean; eventAlerts: boolean;
+ dailySummaryUtcHour: number; chatId: string; queued: number; sent: number; failed: number;
+ lastDeliveredUtc: string | null; lastError: string };
+ secrets: { state: "open" | "empty" | "locked" | "localKey"; etoro: { demo: SecretInfo; live: SecretInfo }; telegram: SecretInfo;
+ passwordSource: "ENCELADO_PASSWORD" | "ENCELADO_WEB_TOKEN" | "none"; ignoredEnv: string[]; importNote: string };
+ process: { version: string; informationalVersion: string; commit: string; buildDate: string; dotnet: string; os: string;
+ container: boolean; pid: number; serverUptimeSeconds: number; workingSetBytes: number; gcHeapBytes: number;
+ gen0: number; gen1: number; gen2: number; gcPauseTimePct: number | null; threadPoolThreads: number; timeZone: string };
+ disk: { configPath: string; strategyPath: string; dataPath: string; knowledgePath: string; reportsPath: string; logFile: string;
+ freeBytes: number | null; totalBytes: number | null; writable: boolean; checkedUtc: string; logBytes: number | null };
+ log: { enqueued: number; dropped: number; bufferLines: number; bufferCapacity: number; level: string };
+ web: { sseClients: number; framesSent: number; lastFrameBytes: number };
+ about: { name: "Encelado"; author: "Alberto Balbo"; version: string; buildDate: string; commit: string; license: string; docs: string } }
+
+type SecretInfo = { present: boolean; masked: string; savedUtc: string | null };
+```
+
+### `GET /api/learning`
+
+Il rapporto sull'apprendimento. La parte viva la pubblica il motore (immutabile); a motore fermo e per i file di `knowledge/` la legge dal disco in sola lettura. Query: `features=all` aggiunge il vettore completo per basket.
+
+```ts
+{ schema: 1; generatedUtc: string; source: "engine" | "disk"; engineState: string;
+ status: { mode: "ombra-disabilitato" | "ombra" | "attivo"; enabled: boolean; weeklyCycle: boolean; challengerEnabled: boolean;
+ activeFlag: boolean; gateEffective: boolean; champion: string; modelVersion: number; seen: number;
+ pMin: number; deactivationAuc: number; lastReport: string; reason: string; trackedEntries: number };
+ dataset: null | { computedUtc: string; datasetHash: string; closedRows: number; labelledRows: number; withoutEntryRow: number;
+ entryRowsWithoutFeatures: number; loneLegRows: number; correctedRows: number; unverifiedRows: number;
+ wins: number; losses: number; winRate: number | null; pnlNetUsd: number; meanPnlUsd: number | null;
+ medianPnlUsd: number | null; p5PnlUsd: number | null; firstOpenedUtc: string | null; lastClosedUtc: string | null;
+ demoClosed: number; activationTarget: number; activationProgress: number;
+ byMode: Array<{ key: string; count: number }>;
+ byBasket: GroupStats[]; byPreset: GroupStats[]; byExitReason: GroupStats[];
+ labelsSuspect: boolean; labelsSuspectReason: string };
+ activation: { passesWalkForward: boolean; passesAdr0006: boolean; operatorEnabled: boolean; motivazione: string;
+ items: Array<{ key: string; label: string; current: string; required: string; ok: boolean | null; source: string }> };
+ logistic: { inputs: number; seen: number; learningRate0: number; currentLearningRate: number; l2: number; bias: number;
+ weightNorm: number; standardizerRows: number; standardizerHalfLifeRows: number;
+ weights: Array<{ index: number; name: string; label: string; weight: number; mean: number; stdDev: number }> }; // per |peso| decrescente
+ challenger: null | { hidden: number; seed: number; seen: number; outputBias: number; w1Norm: number; w2Norm: number;
+ silentUnits: number; standardizerRows: number; challengerWins: boolean };
+ lastCycle: null | { version: number; utc: string; durationMs: number; trigger: "settimanale" | "manuale" | "offline"; rows: number;
+ datasetHash: string; trainedOnUntilUtc: string | null; logistic: ModelEvaluation; mlp: ModelEvaluation | null; challengerWins: boolean };
+ rolling: { count: number; pAt: "entry" | "close"; auc100: number | null; auc200: number | null; auc100Low: number | null; auc100High: number | null;
+ brier100: number | null; logLoss100: number | null; hitRate100: number | null; meanP100: number | null; lastOutcomes10: number | null;
+ recentP: number[]; recentLabel: number[]; aucHistory: Array<{ utc: string; auc100: number }>; calibration: CalibrationBin[] };
+ baskets: Array<{ basket: string; cross: string; enabled: boolean; state: string; pMl: number | null; pMlUtc: string | null;
+ pMlKind: "ultima barra" | "all'ingresso" | ""; wouldBeFiltered: boolean;
+ topContributions: Array<{ index: number; name: string; label: string; value: number | null; z: number | null; contribution: number | null }>;
+ features: Array<{ index: number; name: string; label: string; value: number | null; z: number | null; contribution: number | null }> | null;
+ vol: null | { bars: number; activeModel: string; ewmaSigma: number | null; harSigma: number | null; forecastSigma: number | null;
+ average30dSigma: number | null; volRatio: number | null; zInScale: number | null; rmseEwma: number | null;
+ rmseHar: number | null; scored: number; pending: number; lastHarFitUtc: string | null; context: number; contextLabel: string } }>;
+ bandit: { contexts: number; explorationCap: number; choices: number; explorations: number; explorationShare: number | null;
+ currentPreset: string; applied: false; rewardsSuspect: boolean;
+ arms: Array<{ context: number; contextLabel: string; preset: string; alpha: number; beta: number; successes: number; failures: number;
+ n: number; mean: number; low95: number; high95: number; bestInContext: boolean }>;
+ lastProposal: null | { utc: string; context: number; preset: string; explored: boolean; means: number[]; text: string } };
+ volatility: null | { historyCount: number; tercileLow: number | null; tercileHigh: number | null };
+ knowledge: { calibration: Array<{ dimension: string; bucket: string; count: number; winRate: number | null; meanPnl: number | null; totalPnl: number | null; motivazione: string }>;
+ proposals: Array<{ utc: string; origin: string; parameter: string; currentValue: string; proposedValue: string; evidence: string; state: string; motivazione: string; basedOnSuspectData: boolean }>;
+ registry: Array<{ version: string; utc: string; type: string; nTrain: number; aucWf: number | null; brier: number | null; logLoss: number | null; state: string; motivazione: string }>;
+ insights: null | { fileName: string; modifiedUtc: string; markdown: string; truncated: boolean };
+ modelFiles: Array<{ name: string; bytes: number; modifiedUtc: string; kind: string; version: number | null; rows: number | null }>;
+ files: Array<{ name: string; bytes: number; modifiedUtc: string }> };
+ schedule: { lastCycleUtc: string | null; nextDueUtc: string | null; runsInBot: boolean; due: boolean; running: boolean;
+ runningSinceUtc: string | null; runningPhase: string; lastDurationMs: number | null; lastError: string; lastTrigger: string };
+ warnings: string[] }
+
+type GroupStats = { key: string; count: number; winRate: number | null; pnlNetUsd: number; meanPnlUsd: number | null };
+type CalibrationBin = { lower: number; upper: number; count: number; meanPredicted: number | null; observedRate: number | null };
+type ModelEvaluation = { model: string; rows: number; burnIn: number; auc: number | null; aucLow: number | null; aucHigh: number | null;
+ brier: number | null; logLoss: number | null; calibration: CalibrationBin[]; pnlAllUsd: number; pnlFilteredUsd: number;
+ filteredCount: number; sharpeAll: number | null; sharpeFiltered: number | null; dsrFiltered: number | null;
+ passesActivation: boolean; motivazione: string };
+```
+
+### `GET /api/log?level=&q=&limit=&after=`
+
+`level`: `tutti` (default), `info`, `warn`, `error` (minimo). `q`: testo. `limit`: default 500, massimo 5000. `after`: solo le righe con `seq` maggiore.
+
+```ts
+{ lastSeq: number; file: string;
+ rows: Array<{ seq: number; timeUtc: string; time: string; level: string; source: string; message: string }> }
+// message è sempre su una riga: gli a capo diventano " ⏎ "
+```
+
+### Storico (invariato dalla 5.0)
+
+`GET /api/history/orders | positions | periods` con i filtri `from`, `to`, `basket`, `symbol`, `outcome`, `origin` e `format=csv`. Forma delle righe come in `src/Encelado.Server/Web/WebHost.cs` (la pagina Storico della 5.0).
+
+## Comandi
+
+`POST /api/commands/{nome}` con corpo JSON facoltativo. Risposta `{ ok, message, needsPhrase, code?, … }`: `needsPhrase` è `true` (HTTP **409**) quando serve la frase `CONFERMO LIVE`; `code` (se presente) è `needsPhrase`, `restart` o `refused`.
+
+| Nome | Corpo | Effetto |
+|---|---|---|
+| `start` | `{ confirm?: string }` | Avvia il motore. In modalità Live serve `confirm = "CONFERMO LIVE"` (409 `needsPhrase` altrimenti). |
+| `stop` | — | Ferma il motore; i basket restano sul conto salvo `run.closeOnShutdown`. |
+| `close` | `{ argument: "EURUSD/USDCHF" }` | Chiude il basket. |
+| `kill` | `{ foreign?: boolean }` | Kill-switch; `foreign` chiude anche le posizioni esterne. Risposta con `positions[]` residue. |
+| `reset` | `{ reason: string }` | Ripristino in cinque passi; risposta con `steps[]`. |
+| `residue` | `{ argument?: "all" \| "" }` | Richiude i residui del kill-switch. |
+| `pause`, `resume` | — | Pausa/ripresa delle entrate. |
+| `bonifica` | `{ argument: "list" \| "close:" }` | Elenco o chiusura delle orfane; `positions[]`. |
+| `learn` | — | Ciclo di apprendimento (in background; a motore fermo come manutenzione). |
+
+Il comando `preset` non esiste più: il preset si cambia in Impostazioni.
+
+## Impostazioni
+
+### `GET /api/settings`
+
+```ts
+{ configPath: string; strategyPath: string;
+ version: number; // cambia a ogni salvataggio (impostazioni o segreti)
+ engine: { state: string; account: "demo" | "live"; running: boolean };
+ groups: Array<{ key: string; title: string; description: string; target: "config" | "strategy"; advanced: boolean;
+ // key: "conto" | "esecuzione" | "strategia" | "avanzate" | "telegram" | "interfaccia" | "log"
+ fields: Array<{ path: string; // "run.pollSeconds" oppure "strategy:preset"
+ label: string; kind: "text" | "number" | "integer" | "choice" | "bool" | "list";
+ value: string; // sempre stringa; bool = "true"/"false"; list = valori separati da virgola
+ options: string[]; // per choice
+ suffix: string; tooltip: string; readOnly: boolean; error: string;
+ scope: "immediate" | "engine" | "restart"; // quando ha effetto
+ min: number | null; max: number | null;
+ allowEmpty: boolean }> }>; // vuoto ammesso: per un numero significa "il valore del preset" (la chiave sparisce dal file)
+ secrets: { state: "open" | "empty" | "locked" | "localKey"; etoro: { demo: SecretInfo; live: SecretInfo }; telegram: SecretInfo;
+ passwordSource: string; ignoredEnv: string[];
+ importNote: string; // cosa ha fatto l'importazione una tantum dalla 5.0 (vuoto se niente)
+ problem: string } } // perché i segreti sono bloccati (vuoto altrimenti)
+```
+
+L'input è tollerante: un numero può avere la virgola decimale (`0,65`), un booleano può essere `sì`/`no`; il valore restituito è sempre normalizzato (`0.65`, `true`). Le stringhe arrivano già in italiano.
+
+### `POST /api/settings`
+
+Corpo `{ "edits": { "": "", … }, "confirm"?: "CONFERMO LIVE" }` (accettato anche l'oggetto piatto `{ "": "" }` della 5.0).
+
+Risposta:
+
+```ts
+{ ok: boolean; message: string;
+ results: Array<{ path: string; applied: "immediate" | "engine" | "restart" | "stored" | "error"; message: string }>;
+ restart: "none" | "done" | "needsPhrase" | "refused";
+ needsPhrase: boolean; // = restart === "needsPhrase"
+ errors: Record; // path → errore di validazione ("*" = la combinazione dei valori)
+ version: number }
+```
+
+Con `restart = "needsPhrase"` (HTTP 409) niente è stato scritto: il client chiede la frase e ripete con `confirm`. Con `restart = "refused"` (HTTP 409) niente è stato scritto: il cambio di conto (o delle coppie dei basket) è rifiutato finché ci sono basket aperti, in attesa o ordini senza esito, oppure mancano le chiavi del conto scelto a motore acceso. Valori non validi: HTTP 400 con `errors`.
+
+### Segreti
+
+| Rotta | Corpo | Effetto |
+|---|---|---|
+| `POST /api/settings/keys` | `{ account: "demo" \| "live", apiKey, userKey }` | Verifica le chiavi su quel conto (profilo e saldo) e le salva cifrate. Se è il conto attivo e il motore gira, lo riavvia (Live: serve `confirm`). |
+| `DELETE /api/settings/keys?account=demo` | — | Rimuove le chiavi di quel conto (a motore fermo, o del conto non attivo). |
+| `POST /api/settings/telegram-token` | `{ token }` | Verifica con `getMe` e salva cifrato; riconfigura Telegram subito. |
+| `DELETE /api/settings/telegram-token` | — | Rimuove il token; Telegram si spegne. |
+| `POST /api/settings/telegram-test` | — | Manda un messaggio di prova alla chat configurata. |
+| `POST /api/settings/secrets/unlock` | `{ previous }` | Decifra con la password precedente e ricifra con quella attuale. |
+| `POST /api/settings/secrets/reset` | — | Ricomincia con un deposito vuoto (il vecchio file resta come `.bak`). |
+| `POST /api/settings/restore` | — | Valori di fabbrica di `encelado.json` (a motore fermo; backup con la data). |
+
+Ogni rotta dei segreti risponde `{ ok, message, restart, needsPhrase, detail, version }`: `detail` è ciò che la verifica ha trovato (utente ed equity del conto, nome del bot Telegram) o il percorso del backup. Chiavi rifiutate da eToro o token rifiutato da Telegram: HTTP 400, niente salvato. Deposito bloccato o chiavi del conto in uso a motore acceso: HTTP 409.
+
+## Salute
+
+`GET /api/health` (libera, per il `HEALTHCHECK` del container):
+
+```ts
+{ ok: boolean; state: string; apiState: string; heartbeatAgeSeconds: number | null; diskWritable: boolean; uptimeSeconds: number }
+```
+
+`ok` è falso se il disco dei dati non è scrivibile o se, a motore acceso, l'heartbeat è più vecchio di 105 s.
diff --git a/Encelado/scripts/run-dev.ps1 b/Encelado/scripts/run-dev.ps1
index 24ef74c..2f8617e 100644
--- a/Encelado/scripts/run-dev.ps1
+++ b/Encelado/scripts/run-dev.ps1
@@ -4,10 +4,10 @@
.DESCRIPTION
Stessa disposizione del container: deploy/local/config (encelado.json, strategy.json,
- chiavi cifrate) e deploy/local/data (ledger, stato, log). La cartella è ignorata da git.
- Senza ENCELADO_WEB_TOKEN il server ascolta solo su localhost e non chiede il login.
- Le chiavi eToro: variabili ETORO_API_KEY/ETORO_USER_KEY già nell'ambiente, oppure
- Impostazioni ▸ Chiavi eToro con ENCELADO_KEY_PASSPHRASE impostata.
+ segreti cifrati) e deploy/local/data (ledger, stato, log). La cartella è ignorata da git.
+ La password dell'interfaccia è "sviluppo", come nel compose: i segreti cifrati della
+ sandbox restano leggibili in entrambi i modi. Conto, chiavi eToro dei due conti e
+ Telegram si impostano da Impostazioni nella pagina.
scripts\run-dev.ps1 # motore fermo: premi AVVIA nella pagina
scripts\run-dev.ps1 -Autostart # motore avviato subito (servono le chiavi)
@@ -27,6 +27,7 @@ Set-Location $root
$env:ENCELADO_CONFIG_DIR = Join-Path $root "deploy\local\config"
$env:ENCELADO_DATA_DIR = Join-Path $root "deploy\local\data"
$env:ENCELADO_WEB_PORT = "$Port"
+$env:ENCELADO_PASSWORD = "sviluppo"
New-Item -ItemType Directory -Force $env:ENCELADO_CONFIG_DIR, $env:ENCELADO_DATA_DIR | Out-Null
dotnet build src/Encelado.Server -c Debug -nologo -v q
@@ -35,8 +36,8 @@ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$args = @()
if ($Sample) { $args += "--sample" } elseif (-not $Autostart) { $args += "--no-autostart" }
$url = "http://localhost:$Port/"
-Write-Host "Encelado in locale: $url (configurazione in deploy\local\config, dati in deploy\local\data)" -ForegroundColor Cyan
-Write-Host "Comandi da tastiera: status, close , kill, residuo, preset , reset , bonifica, stop. Ctrl+C = arresto." -ForegroundColor DarkGray
+Write-Host "Encelado in locale: $url password: sviluppo (configurazione in deploy\local\config, dati in deploy\local\data)" -ForegroundColor Cyan
+Write-Host "Comandi da tastiera: status, close , kill, residuo, reset , bonifica, stop. Ctrl+C = arresto." -ForegroundColor DarkGray
if (-not $NoBrowser) { Start-Job -ScriptBlock { param($u) Start-Sleep -Seconds 3; Start-Process $u } -ArgumentList $url | Out-Null }
dotnet src/Encelado.Server/bin/Debug/net10.0/Encelado.Server.dll @args
diff --git a/Encelado/scripts/run-dev.sh b/Encelado/scripts/run-dev.sh
index e9064be..c63d14b 100644
--- a/Encelado/scripts/run-dev.sh
+++ b/Encelado/scripts/run-dev.sh
@@ -4,12 +4,14 @@
# sh scripts/run-dev.sh # engine stopped: press AVVIA in the page
# sh scripts/run-dev.sh --sample # fake data, no keys: to look at the pages
# sh scripts/run-dev.sh --autostart # engine started at once (keys needed)
-# Without ENCELADO_WEB_TOKEN the server listens on localhost only and asks no login.
+# The interface password is "sviluppo", as in docker-compose.yml: the encrypted secrets of
+# the sandbox (eToro keys, Telegram token, entered from Impostazioni) stay readable both ways.
set -eu
cd "$(dirname "$0")/.."
export ENCELADO_CONFIG_DIR="$(pwd)/deploy/local/config"
export ENCELADO_DATA_DIR="$(pwd)/deploy/local/data"
export ENCELADO_WEB_PORT="${ENCELADO_WEB_PORT:-8080}"
+export ENCELADO_PASSWORD="sviluppo"
mkdir -p "$ENCELADO_CONFIG_DIR" "$ENCELADO_DATA_DIR"
MODE="--no-autostart"
@@ -21,5 +23,5 @@ for a in "$@"; do
done
dotnet build src/Encelado.Server -c Debug -nologo -v q
-echo "Encelado in locale: http://localhost:$ENCELADO_WEB_PORT/ (config in deploy/local/config, dati in deploy/local/data)"
+echo "Encelado in locale: http://localhost:$ENCELADO_WEB_PORT/ password: sviluppo (config in deploy/local/config, dati in deploy/local/data)"
exec dotnet src/Encelado.Server/bin/Debug/net10.0/Encelado.Server.dll $MODE
diff --git a/Encelado/scripts/run-docker.ps1 b/Encelado/scripts/run-docker.ps1
index d035c7b..010e699 100644
--- a/Encelado/scripts/run-docker.ps1
+++ b/Encelado/scripts/run-docker.ps1
@@ -4,10 +4,10 @@
.DESCRIPTION
Le cartelle deploy/local/config e deploy/local/data vengono montate come /config e /data:
- sono le stesse di scripts\run-dev.ps1, quindi configurazione e chiavi salvate valgono
- in entrambi i modi. Il token dell'interfaccia è "sviluppo" salvo ENCELADO_WEB_TOKEN in
- un file .env accanto alla compose (dove vanno anche ETORO_API_KEY, ETORO_USER_KEY,
- TELEGRAM_*). Segue il log finché non premi Ctrl+C; il container resta acceso:
+ sono le stesse di scripts\run-dev.ps1, quindi configurazione e segreti salvati valgono
+ in entrambi i modi. La password dell'interfaccia è "sviluppo" salvo ENCELADO_PASSWORD in
+ un file .env accanto alla compose; conto, chiavi eToro e Telegram si impostano dalla
+ pagina Impostazioni. Segue il log finché non premi Ctrl+C; il container resta acceso:
scripts\run-docker.ps1 -Down per fermarlo (SIGTERM, stop pulito).
scripts\run-docker.ps1 # build + up -d + log
@@ -27,14 +27,13 @@ if ($Down) { docker compose down; exit $LASTEXITCODE }
New-Item -ItemType Directory -Force "deploy\local\config", "deploy\local\data" | Out-Null
$env:GIT_COMMIT = (git rev-parse --short=12 HEAD 2>$null); if (-not $env:GIT_COMMIT) { $env:GIT_COMMIT = "n/d" }
-$env:PUID = "1000"; $env:PGID = "1000"
if ($NoBuild) { docker compose up -d } else { docker compose up -d --build }
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$port = if ($env:ENCELADO_WEB_PORT) { $env:ENCELADO_WEB_PORT } else { "8080" }
-$token = if ($env:ENCELADO_WEB_TOKEN) { "(da ENCELADO_WEB_TOKEN)" } else { "sviluppo" }
+$password = if ($env:ENCELADO_PASSWORD) { "(da ENCELADO_PASSWORD)" } else { "sviluppo" }
$url = "http://localhost:$port/"
-Write-Host "Encelado nel container: $url token: $token (docker compose down per fermare)" -ForegroundColor Cyan
+Write-Host "Encelado nel container: $url password: $password (docker compose down per fermare)" -ForegroundColor Cyan
if (-not $NoBrowser) { Start-Job -ScriptBlock { param($u) Start-Sleep -Seconds 4; Start-Process $u } -ArgumentList $url | Out-Null }
docker compose logs -f encelado
diff --git a/Encelado/scripts/run-docker.sh b/Encelado/scripts/run-docker.sh
index 1b0da4d..d605fd6 100644
--- a/Encelado/scripts/run-docker.sh
+++ b/Encelado/scripts/run-docker.sh
@@ -1,7 +1,8 @@
#!/usr/bin/env sh
# Builds the image and starts Encelado in the container with the docker-compose.yml at the root.
# deploy/local/config and deploy/local/data are mounted as /config and /data (the same
-# folders scripts/run-dev.sh uses). Token "sviluppo" unless ENCELADO_WEB_TOKEN is in .env.
+# folders scripts/run-dev.sh uses). Interface password "sviluppo" unless ENCELADO_PASSWORD
+# is in .env; account, eToro keys and Telegram are set from the Impostazioni page.
# sh scripts/run-docker.sh # build + up -d + follow the log (Ctrl+C leaves it running)
# sh scripts/run-docker.sh --no-build
# sh scripts/run-docker.sh --down # docker compose down (SIGTERM, clean stop)
@@ -12,7 +13,6 @@ case "${1:-}" in
esac
mkdir -p deploy/local/config deploy/local/data
export GIT_COMMIT="$(git rev-parse --short=12 HEAD 2>/dev/null || echo n/d)"
-export PUID="${PUID:-1000}" PGID="${PGID:-1000}"
if [ "${1:-}" = "--no-build" ]; then docker compose up -d; else docker compose up -d --build; fi
-echo "Encelado nel container: http://localhost:${ENCELADO_WEB_PORT:-8080}/ token: ${ENCELADO_WEB_TOKEN:-sviluppo} (sh scripts/run-docker.sh --down per fermare)"
+echo "Encelado nel container: http://localhost:${ENCELADO_WEB_PORT:-8080}/ password: ${ENCELADO_PASSWORD:-sviluppo} (sh scripts/run-docker.sh --down per fermare)"
exec docker compose logs -f encelado
diff --git a/Encelado/src/Encelado.Core/Baskets/Backtest/BasketBacktest.cs b/Encelado/src/Encelado.Core/Baskets/Backtest/BasketBacktest.cs
index 216c5ff..401b09c 100644
--- a/Encelado/src/Encelado.Core/Baskets/Backtest/BasketBacktest.cs
+++ b/Encelado/src/Encelado.Core/Baskets/Backtest/BasketBacktest.cs
@@ -166,7 +166,7 @@ public sealed record BacktestResult(
/// What the replay cannot do, and says so: the economic-calendar blackout and the
/// sentiment features need history the free feeds do not provide, so in the backtest
/// they are absent (no blackout applied). The live bot applies them; the comparison
-/// backtest → paper → forward is where their effect shows.
+/// backtest → demo account → forward is where their effect shows.
///
///
public static class BasketBacktest
diff --git a/Encelado/src/Encelado.Core/Baskets/Backtest/BasketTrials.cs b/Encelado/src/Encelado.Core/Baskets/Backtest/BasketTrials.cs
index f717363..962f0e3 100644
--- a/Encelado/src/Encelado.Core/Baskets/Backtest/BasketTrials.cs
+++ b/Encelado/src/Encelado.Core/Baskets/Backtest/BasketTrials.cs
@@ -90,72 +90,7 @@ public static class BasketTrials
{
ArgumentNullException.ThrowIfNull(c);
BasketStrategyConfig copy = BasketStrategyConfig.ParseText(BasketStrategyConfig.DefaultJson, out _);
- copy.Risk = new RiskOptions
- {
- MaxMarginUsePct = c.Risk.MaxMarginUsePct,
- MaxMarginPerBasketPct = c.Risk.MaxMarginPerBasketPct,
- MarginBufferPct = c.Risk.MarginBufferPct,
- CloseForeignOnKill = c.Risk.CloseForeignOnKill,
- MarginCallBlockRatio = c.Risk.MarginCallBlockRatio,
- MarginCallCloseRatio = c.Risk.MarginCallCloseRatio,
- };
- copy.Recovery = new RecoveryOptions { ThresholdMinutes = c.Recovery.ThresholdMinutes, WarmupMinutes = c.Recovery.WarmupMinutes, HeartbeatSeconds = c.Recovery.HeartbeatSeconds };
- copy.Learning = new LearningOptions { Enabled = c.Learning.Enabled, WeeklyCycle = c.Learning.WeeklyCycle, Challenger = c.Learning.Challenger };
- copy.Preset = c.Preset;
- copy.SignalMode = c.SignalMode;
- copy.ExitMode = c.ExitMode;
- copy.AveragingMode = c.AveragingMode;
- copy.TpMode = c.TpMode;
- copy.SameCrossPolicy = c.SameCrossPolicy;
- copy.PreferDirectCross = c.PreferDirectCross;
- copy.InvertSignal = c.InvertSignal;
- copy.Window = c.Window;
- copy.WindowShort = c.WindowShort;
- copy.RhoMin = c.RhoMin;
- copy.RhoShortMin = c.RhoShortMin;
- copy.HalfLifeMinBars = c.HalfLifeMinBars;
- copy.HalfLifeMaxBars = c.HalfLifeMaxBars;
- copy.HalfLifeRecalcHours = c.HalfLifeRecalcHours;
- copy.AtrPeriod = c.AtrPeriod;
- copy.EwmaSpan = c.EwmaSpan;
- copy.TrendPeriod = c.TrendPeriod;
- copy.ZOut = c.ZOut;
- copy.DIn = c.DIn;
- copy.AnchorBars = c.AnchorBars;
- copy.GridStepZ = c.GridStepZ;
- copy.LotMultiplier = c.LotMultiplier;
- copy.MaxLossPerBasketPct = c.MaxLossPerBasketPct;
- copy.RhoBreak = c.RhoBreak;
- copy.RhoBreakBars = c.RhoBreakBars;
- copy.MaxHoldingBars = c.MaxHoldingBars;
- copy.TpAtrMultiple = c.TpAtrMultiple;
- copy.CostMultiple = c.CostMultiple;
- copy.SpreadMedianMultiple = c.SpreadMedianMultiple;
- copy.SpreadAnomalyMultiple = c.SpreadAnomalyMultiple;
- copy.SlippagePipsPerLeg = c.SlippagePipsPerLeg;
- copy.OvernightPipsPerDay = c.OvernightPipsPerDay;
- copy.BlackoutBeforeMin = c.BlackoutBeforeMin;
- copy.BlackoutAfterMin = c.BlackoutAfterMin;
- copy.FridayCutoffUtcHour = c.FridayCutoffUtcHour;
- copy.OpenDelayMinutes = c.OpenDelayMinutes;
- copy.Sessions = [.. c.Sessions];
- copy.MaxEffectiveLeverage = c.MaxEffectiveLeverage;
- copy.OrderLeverage = c.OrderLeverage;
- copy.VolScaleMin = c.VolScaleMin;
- copy.VolScaleMax = c.VolScaleMax;
- copy.VolAverageDays = c.VolAverageDays;
- copy.MlMinProbability = c.MlMinProbability;
- copy.EquityStopPct = c.EquityStopPct;
- copy.DailyLossPct = c.DailyLossPct;
- copy.LegTimeoutSec = c.LegTimeoutSec;
- copy.ClockSkewMaxSeconds = c.ClockSkewMaxSeconds;
- copy.ZInOverride = c.ZInOverride;
- copy.RiskPerBasketPctOverride = c.RiskPerBasketPctOverride;
- copy.MaxBasketsOverride = c.MaxBasketsOverride;
- copy.TpPipsOverride = c.TpPipsOverride;
- copy.MaxAddsOverride = c.MaxAddsOverride;
- copy.ZStopOverride = c.ZStopOverride;
- copy.Baskets = [.. c.Baskets.Select(static b => new BasketDefinition { A = b.A, B = b.B, Enabled = b.Enabled, Note = b.Note })];
+ copy.CopyFrom(c);
return copy;
}
diff --git a/Encelado/src/Encelado.Core/Baskets/BasketDecider.cs b/Encelado/src/Encelado.Core/Baskets/BasketDecider.cs
index d99ea48..c3c845d 100644
--- a/Encelado/src/Encelado.Core/Baskets/BasketDecider.cs
+++ b/Encelado/src/Encelado.Core/Baskets/BasketDecider.cs
@@ -211,8 +211,24 @@ public sealed class BasketDecider
public BasketPreset Preset => _preset;
- /// 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("