5.1: interfaccia corretta dopo la revisione: kill-switch che fa quello che l'operatore sceglie, impostazioni salvabili dopo due modifiche, stati dei basket spenti non più nascosti, parole del ledger in italiano

- Kill-switch: la casella «chiudi anche le esterne» parte come l'impostazione (tick.closeForeignOnKill), con una riga che lo dice, e il dialogo manda sempre foreign esplicito: la scelta fatta lì è quella che succede. Nelle conferme distruttive il fuoco parte su «Annulla», così un Invio tenuto premuto non esegue un kill-switch o una chiusura.
- Impostazioni: una modifica si giudica contro il valore che il server ha adesso, non contro quello di quando la pagina è stata costruita; dopo due salvataggi tornare al valore di prima si vede come modifica e si può salvare.
- Basket: vale la parola del server; un basket spento in Attesa B, Errore o Uscita lo dice ed è attenuato solo quando è spento e senza niente sul conto.
- Storico e Mercato: un filtro ricordato resta visibile e annullabile (opzioni ricostruite al primo tick, strumenti dai basket anche a motore fermo, un chip per ogni valuta ricordata).
- Mercato: bid, ask, spread ed età degli strumenti dei basket seguono il tick ogni secondo, l'età delle coppie di conversione cresce con l'orologio. Dashboard e Apprendimento mostrano «—» per una quotazione mai arrivata e per i terzili sconosciuti, non 0.
- Contratto condiviso: righe del registro in dashboard da tick.statusLines, perdita giornaliera bloccata fino alle 00:00 UTC (dailyLossLatched) su tessera, allarme e pallino, heartbeat giudicato sul suo intervallo (heartbeatSeconds, soglia di /api/health), Content-Type: application/json su ogni POST e DELETE anche senza corpo.
- labels.js: evento del ledger, codici di motivo, motivi d'uscita, stati degli ordini, vincolo della size e sorgenti del log in italiano (Basket, Storico, Log, Apprendimento, Posizioni), il codice resta nel tooltip. Icona «list» per il registro dei modelli e nessuna X al posto di un'icona sconosciuta.
- UI_GUIDELINES: le regole nuove (casella del kill-switch, fuoco, labels.js, statusLines, Content-Type, controllo dei moduli con node --check su copie .mjs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-09-30 23:17:22 +02:00
1 parent 07a00cd91c
commit b80638d949
19 files changed
+456 -114

No files matched your search

+35 -19
View File
@@ -31,9 +31,12 @@ campi valgono lì.
rifiutato (`{ ok: false }`, anche i 400 della modalità `--sample`) apre la finestra con il messaggio del server.
8. **I bottoni delle barre strumenti sono icone** con `title` e `aria-label`. Le azioni principali di una pagina sono
bottoni con testo: Salva, Esegui ciclo, Bonifica orfane.
9. **Le azioni irreversibili chiedono conferma**: chiusura di un basket, kill-switch (con la casella «chiudi anche le
esterne» spenta), ripristino (motivazione di almeno 10 caratteri), rimozione di chiavi e token, valori di
fabbrica, avvio Live e ogni modifica che riavvia il motore in Live (frase `CONFERMO LIVE` scritta per intero).
9. **Le azioni irreversibili chiedono conferma**: chiusura di un basket, kill-switch, ripristino (motivazione di almeno
10 caratteri), rimozione di chiavi e token, valori di fabbrica, avvio Live e ogni modifica che riavvia il motore in
Live (frase `CONFERMO LIVE` scritta per intero). Nelle conferme distruttive il fuoco parte su «Annulla»: un Invio
tenuto premuto non esegue niente. Nel kill-switch la casella «chiudi anche le esterne» parte come l'impostazione
«Il kill-switch chiude anche le posizioni esterne» (`tick.closeForeignOnKill`, con una riga che lo dice quando è
accesa) e la scelta fatta nel dialogo è quella che vale: va sempre al server come `foreign` esplicito.
10. **Testi italiani, brevi.** «Non mettere scritte inutili che occupano solo spazio»: i dettagli vanno nel tooltip,
nel log o nella pagina di dettaglio.
@@ -88,6 +91,8 @@ wwwroot/js/charts.js gauge dello z, barre, barre centrate sullo zero, spa
wwwroot/js/dialog.js finestra centrale: conferma, richiesta di testo (CONFERMO LIVE), messaggi
wwwroot/js/actions.js AVVIA, FERMA, KILL, chiudi basket, residui, ripristino, pausa, bonifica, ciclo di apprendimento, esci
wwwroot/js/baskets.js come si legge un basket (stato, verso, p_ML, prossimo evento nel fuso del browser)
wwwroot/js/labels.js le parole del ledger e del motore in italiano (evento, codici di motivo, motivi d'uscita,
stati degli ordini, sorgenti del log); il codice resta nel tooltip
wwwroot/js/icons.js flags.js clocks.js split.js
wwwroot/js/pages/<pagina>.js una pagina = { mount(section, ctx, params), unmount(), render(tick), params(p)? }
```
@@ -108,8 +113,8 @@ Da sinistra a destra:
2. Logo e «Encelado».
3. **Pill del motore**: il pallino dice lo stato, il testo il conto. Sostituisce le scritte «demo» e «in esecuzione»
che nella 5.0 stavano in fondo al menu.
- Pallino verde: in esecuzione. Grigio: fermo. Ambra: in avvio o in arresto, pausa, entrate bloccate, recupero.
Rosso: errore o bloccato.
- Pallino verde: in esecuzione. Grigio: fermo. Ambra: in avvio o in arresto, pausa, entrate bloccate, recupero,
perdita giornaliera, heartbeat in ritardo sul suo intervallo (`tick.heartbeatSeconds`). Rosso: errore o bloccato.
- Testo `DEMO` con bordo accento, oppure `LIVE` su fondo rosso.
- Il tooltip dà lo stato completo; il clic apre Sistema.
4. **Pill eToro**: pallino secondo `health.api` e latenza. Il tooltip dà scarto dell'orologio e quota più usata.
@@ -170,7 +175,7 @@ Una riga sotto la barra, solo quando c'è un allarme da spiegare. Gli allarmi, i
| segreti bloccati | rosso | Apri impostazioni |
| nessuna chiave salvata (`health.secrets = empty`, motore fermo) | ambra | Apri impostazioni |
| non riconciliato | ambra | Posizioni |
| perdita giornaliera | ambra | |
| perdita giornaliera (fino alle 00:00 UTC anche se l'equity recupera: `dailyLossLatched`) | ambra | |
| entrate bloccate | ambra | |
| pausa | ambra | Riprendi |
| recupero | ambra | |
@@ -206,7 +211,9 @@ Ogni pagina ha:
- **Schede**: `.tabs`, per il pannello del Basket.
- **Stati**:
- `.chip` (26 px) con `.dot` e icona (14 px) nella barra in alto;
- `.tag` per lo stato di una riga (Aperto verde, Attesa ambra, Inattivo tenue, Errore rosso);
- `.tag` per lo stato di una riga (Aperto verde, Attesa ambra, Inattivo tenue, Errore rosso). Vale la parola del
server: un basket spento in Attesa B, in Errore o in Uscita lo dice, e la riga è attenuata solo se è spento e
senza niente sul conto;
- `.pill`;
- `.lvl` per il livello del log: INFO accento, WARN ambra, ERROR rosso, DEBUG e TRACE tenui.
- **Sezioni**: `.section`, con `h2` alto 38 px (icona, titolo, sottotitolo, strumenti a destra) e corpo `.in` oppure
@@ -237,8 +244,10 @@ Ogni pagina ha:
- curva del realizzato dallo `equitySvg` del server, letto come XML e sanificato.
- **Pannello a destra**: `split.js`, maniglia trascinabile che cambia solo `--panel-w`. Doppio clic ripristina la
larghezza. Sotto 900 px il pannello va sotto l'elenco.
- **Finestre**: `modal()`, `confirmDialog()` (con casella facoltativa), `promptDialog()` (con validazione: il bottone
si abilita solo con il testo giusto), `notice()`. Esc o il clic fuori chiudono; il fuoco resta nella finestra.
- **Finestre**: `modal()`, `confirmDialog()` (con casella facoltativa e una riga di spiegazione), `promptDialog()` (con
validazione: il bottone si abilita solo con il testo giusto), `notice()`. Esc o il clic fuori chiudono; il fuoco resta
nella finestra e parte dal campo di testo, altrimenti dall'ultimo bottone, ma su «Annulla» quando l'azione è
distruttiva.
- **Bandiere**: `flags.js`, sprite SVG iniettato una volta, 18×12 (CH 12×12). Ci sono EU, CH, US, CA, AU, NZ, GB e
JP; il testo è nel tooltip dell'elemento che le contiene.
@@ -246,15 +255,15 @@ Ogni pagina ha:
| Pagina | Dati | Contenuto |
|---|---|---|
| **Dashboard** | tick; `/api/market?calendarDays=7&impact=High,Medium&news=0` | 9 tessere: equity, P&L oggi (con «stima»; è il periodo «oggi» dello Storico), aperto, drawdown con barra verso lo stop, perdita giornaliera con barra, margine, basket con il preset, chiusi oggi, apprendimento con barra. Tabella dei 5 basket: bandiere e nome con il cross, stato, verso, z con gauge, ρ, HL, pip/TP, P&L, costo, p_ML, prossimo evento (ora nel fuso del browser e conto alla rovescia: l'etichetta del motore porta l'ora UTC), chiudi; un clic apre il Basket. Prossimi eventi, mercato (8 quotazioni con lo spread colorato rispetto alla mediana), registro (ultime righe, clic = Log). A 1440×900 sta tutto senza scorrere; da 1500 px di pagina eventi e mercato vanno in una colonna a destra. |
| **Basket** | tick; `/api/baskets/detail?name=` ogni 2 s; `/api/learning` per la scheda ML | Elenco con tutte le colonne (stato, intento, z, z_in, z_stop, ρ_W, ρ_20, HL, pip/TP, P&L, costo, spread×, p_ML, barre, aggiunte, z d'ingresso, evento) e sotto il grafico dello z del basket scelto. Pannello con schede: Stato (intento, ultima decisione con i codici, soglie contro valori con ✓/✗, cost gate, dimensione), Posizione (dati del basket e gambe, oppure la gamba in attesa), Segnale, Contesto, ML (p_ML, contributi, feature), Decisioni (ultime 20). |
| **Dashboard** | tick; `/api/market?calendarDays=7&impact=High,Medium&news=0` | 9 tessere: equity, P&L oggi (con «stima»; è il periodo «oggi» dello Storico), aperto, drawdown con barra verso lo stop, perdita giornaliera con barra (quando scatta resta bloccata fino alle 00:00 UTC anche se l'equity recupera: `dailyLossLatched`, ora di sblocco nel fuso del browser), margine, basket con il preset, chiusi oggi, apprendimento con barra. Tabella dei 5 basket: bandiere e nome con il cross, stato, verso, z con gauge, ρ, HL, pip/TP, P&L, costo, p_ML, prossimo evento (ora nel fuso del browser e conto alla rovescia: l'etichetta del motore porta l'ora UTC), chiudi; un clic apre il Basket. Prossimi eventi, mercato (8 quotazioni con lo spread colorato rispetto alla mediana; «—» per uno strumento non ancora quotato), registro (le ultime `tick.statusLines` righe, cioè Impostazioni ▸ Log ▸ righe di attività, 60 prima del primo tick; clic = Log). A 1440×900 sta tutto senza scorrere; da 1500 px di pagina eventi e mercato vanno in una colonna a destra. |
| **Basket** | tick; `/api/baskets/detail?name=` ogni 2 s; `/api/learning` per la scheda ML | Elenco con tutte le colonne (stato, intento, z, z_in, z_stop, ρ_W, ρ_20, HL, pip/TP, P&L, costo, spread×, p_ML, barre, aggiunte, z d'ingresso, evento) e sotto il grafico dello z del basket scelto. Pannello con schede: Stato (intento, ultima decisione con i motivi, soglie contro valori con ✓/✗, cost gate, dimensione con il vincolo), Posizione (dati del basket e gambe, oppure la gamba in attesa), Segnale, Contesto, ML (p_ML, contributi, feature), Decisioni (ultime 20). Eventi del ledger, codici e vincoli in italiano (`labels.js`), il codice nel tooltip. |
| **Posizioni** | `/api/positions` | Tessere per origine: tutte, basket, orfane del bot, esterne. Ogni posizione del conto: origine, basket e gamba, strumento, verso, unità, apertura, attuale, pip, P&L, margine, leva, SL/TP, aperta da; bonifica delle orfane. Ordini in attesa con la loro età. |
| **Mercato** | `/api/market?calendarDays=7&impact=High,Medium,Low,Holiday&news=50` | Quotazioni (spread, mediana, rapporto, età, ATR, usato da); calendario con filtri per impatto e valuta (ricordati nel browser), conto alla rovescia e blackout; sentiment 1 h, 4 h, 24 h per valuta con risk-off; notizie con i link; valute di visualizzazione; volatilità per basket. |
| **Storico** | `/api/history/orders`, `positions`, `periods` | Tre viste (Ordini, Posizioni, Profitti per periodo con la curva del realizzato), filtri nella barra, esportazione CSV dal server. `#/storico?vista=periodi` apre direttamente una vista. |
| **Mercato** | `/api/market?calendarDays=7&impact=High,Medium,Low,Holiday&news=50`; tick | Quotazioni (spread, mediana, rapporto, età, ATR, usato da): gli strumenti dei basket prendono bid, ask, spread ed età dal tick ogni secondo, l'età delle coppie di sola conversione cresce con l'orologio (la sezione è ricostruita al più ogni 15 s); calendario con filtri per impatto e valuta (ricordati nel browser; una valuta ricordata ha sempre il suo chip, anche in una settimana senza eventi), conto alla rovescia e blackout; sentiment 1 h, 4 h, 24 h per valuta con risk-off; notizie con i link; valute di visualizzazione; volatilità per basket. |
| **Storico** | `/api/history/orders`, `positions`, `periods`; tick | Tre viste (Ordini, Posizioni, Profitti per periodo con la curva del realizzato), filtri nella barra, esportazione CSV dal server. `#/storico?vista=periodi` apre direttamente una vista. I filtri basket e strumento vengono dai basket del tick (anche a motore fermo) e si ricostruiscono quando arriva il primo tick; un filtro ricordato che l'elenco non conosce resta fra le opzioni, visibile e annullabile. Motivi d'uscita e stati degli ordini in italiano, il codice nel tooltip. |
| **Apprendimento** | `/api/learning` | Stato e motivo; «Esegui ciclo» (spento mentre gira, con la fase in corso); esportazione JSON. 10 tessere: etichettati/300, win rate, P&L netto, AUC mobile con intervallo, Brier, modello, bandit, volatilità, ultimo e prossimo ciclo. Avvisi. Poi le sezioni: attivazione (criteri ✓/✗), cosa ha imparato (pesi ordinati, 15 + «mostra tutti»), per basket, bandit 3×3 con il migliore in oro, ultimo ciclo (logistica contro MLP, calibrazione, AUC nel tempo), stato dei modelli, dataset per basket, preset e uscita, calibrazione per fascia, proposte, registro dei modelli, file, osservazioni (Markdown reso in modo sicuro). |
| **Log** | righe del tick; `/api/log` | Barra su una riga: livello, «Cerca…», «Segui», conteggio, nome del file (il percorso intero nel tooltip), esporta. Una riga per messaggio: ora nel fuso del browser, tag del livello colorato, origine, messaggio con i puntini. Il clic apre il testo intero. Al massimo 2000 righe nel DOM. |
| **Sistema** | `/api/system` ogni 3 s | Motore (con Pausa/Riprendi e Ripristino…), collegamento eToro con le quote, feed, Telegram (messaggio di prova), segreti (sblocco e ripartenza, variabili ignorate), processo, disco, log, interfaccia web (Esci), diagnostica (bonifica), informazioni. |
| **Impostazioni** | `/api/settings` | Gruppi disposti in colonne, etichetta a sinistra e controllo a destra, levette per i sì/no, numeri a destra con l'unità, un'icona per l'effetto: ⚡ subito, ⚙ nel motore, ↻ riavvia il motore. Pannelli speciali: chiavi eToro demo e live (gruppo `conto`), token Telegram (`telegram`), Esci (`interfaccia`), segreti bloccati, valori predefiniti; il gruppo `avanzate` è chiuso. «Salva (n)» manda solo i campi cambiati; se serve la frase CONFERMO LIVE la chiede e ripete; l'esito di ogni campo compare accanto per qualche secondo. |
| **Log** | righe del tick; `/api/log` | Barra su una riga: livello, «Cerca…», «Segui», conteggio, nome del file (il percorso intero nel tooltip), esporta. Una riga per messaggio: ora nel fuso del browser, tag del livello colorato, origine in italiano (la classe nel tooltip), messaggio con i puntini e con i codici del ledger in italiano («motivo take-profit»). Il clic apre il testo intero; il tooltip, la ricerca (come il `q` del server) e l'esportazione usano il testo del file. Al massimo 2000 righe nel DOM. |
| **Sistema** | `/api/system` ogni 3 s | Motore (con Pausa/Riprendi e Ripristino…; heartbeat giudicato sul suo intervallo, `heartbeatSeconds`, rosso oltre la soglia di `/api/health`), collegamento eToro con le quote, feed, Telegram (messaggio di prova), segreti (sblocco e ripartenza, variabili ignorate), processo, disco, log, interfaccia web (Esci), diagnostica (bonifica), informazioni. |
| **Impostazioni** | `/api/settings` | Gruppi disposti in colonne, etichetta a sinistra e controllo a destra, levette per i sì/no, numeri a destra con l'unità, un'icona per l'effetto: ⚡ subito, ⚙ nel motore, ↻ riavvia il motore. Pannelli speciali: chiavi eToro demo e live (gruppo `conto`), token Telegram (`telegram`), Esci (`interfaccia`), segreti bloccati, valori predefiniti; il gruppo `avanzate` è chiuso. «Salva (n)» manda solo i campi diversi dal valore che il server ha adesso (riletto a ogni salvataggio: tornare a un valore di prima è una modifica); se serve la frase CONFERMO LIVE la chiede e ripete; l'esito di ogni campo compare accanto per qualche secondo. |
| **Accesso** | `POST /login` | Logo, «Encelado», «Password interfaccia», «Entra»; errore «Password errata.». |
## 7. Flusso dei dati e prestazioni (regole non negoziabili)
@@ -267,7 +276,10 @@ Ogni pagina ha:
`tick.versions[chiave]` e ogni 30 s, con `If-None-Match` (304 gratuito). Il dettaglio del basket si legge ogni 2 s,
Sistema ogni 3 s. Nessun altro polling sotto i 2 s.
- **Le righe del log** arrivano nel tick come differenza e si aggiungono per `seq`. Su un salto o una riconnessione si
recupera il mancante con `/api/log?after=`. Al primo tick si caricano le ultime 300 righe.
recupera il mancante con `/api/log?after=`. Al primo tick si caricano le ultime 300 righe (o `statusLines`, se sono
di più, fino a 2000).
- **Ogni POST e DELETE** (`api()` in `util.js`, l'unica `fetch`) manda `Content-Type: application/json`, anche senza
corpo: il server rifiuta gli altri con 415, così un modulo di un altro sito non può comandare il bot.
- **Tabelle con chiave**: righe create una volta; `textContent`, `title` e `className` scritti solo se diversi. Mai
`innerHTML` con dati: lo usano solo i percorsi statici delle icone. L'SVG del server passa da `DOMParser` in XML e da
una lista di elementi ammessi.
@@ -345,12 +357,16 @@ Lo script compila, avvia `Encelado.Server --sample` su cartelle temporanee e sen
3. Una nuova tabella usa `Grid` con righe a chiave e colonne con larghezza; una nuova sezione a richiesta usa `watch()`
con la sua chiave di `versions`. Un campo nuovo del server si scrive prima in `docs/API.md`.
4. `index.html` e `login.html` restano XML ben formato: elementi chiusi, `hidden="hidden"`, niente `xlink:`.
5. Prima di chiudere:
5. Una parola del ledger o del motore (evento, codice di motivo, motivo d'uscita, stato di un ordine, sorgente del log)
passa da `labels.js`: la parola in italiano sullo schermo, il codice nel tooltip. Un valore che il server può mandare
`null` si mostra «—»: mai un conto fatto su `null` (`null × 1e4` è 0 e si stamperebbe «0,0»).
6. Prima di chiudere:
- `dotnet test`: `EmbeddedUiTests` controlla che le due pagine siano XHTML ben formato, che ogni file citato da
`index.html` e ogni `import` statico dei moduli esista e esporti i nomi importati (un nome mancante blocca tutta
l'app con un `SyntaxError`), che nessun file citi un altro host, che i token abbiano i due temi con gli stessi
nomi, che l'app usi `/api/stream` e chieda `CONFERMO LIVE`, e che il login mandi il campo `password` senza
script; `WebHostTests` che ogni file sia servito con il suo tipo e che l'errore di accesso prenda il posto del
segnaposto;
- `node --check` sui moduli toccati, se Node c'è;
- `node --check` su una copia `.mjs` dei moduli toccati, se Node c'è: su un `.js` Node legge uno script e non vede
gli errori propri dei moduli, come un `import` che si scontra con un `let` e ferma tutta l'app;
- gli screenshot del §10 guardati uno per uno, in entrambi i temi, e la console pulita.
@@ -341,7 +341,7 @@ body.fullpage { display: grid; place-items: center; min-height: 100vh; padding:
.verdict.warn { border-color: var(--warn); color: var(--warn); background: var(--warn-soft); }
.verdict.acc { border-color: var(--accent); color: var(--accent); background: var(--accent-soft); }
.chips { display: flex; flex-wrap: wrap; gap: 4px; }
.code-chip { font-family: var(--mono); font-size: 11px; padding: 1px 6px; border-radius: 4px; background: var(--surface-3); color: var(--muted); white-space: nowrap; }
.code-chip { font-size: var(--fs-tiny); padding: 1px 6px; border-radius: 4px; background: var(--surface-3); color: var(--muted); white-space: nowrap; }
.pre { font-family: var(--mono); font-size: var(--fs-small); color: var(--muted); background: var(--bg); border: 1px solid var(--line); border-radius: 4px; padding: 8px 10px; white-space: pre-wrap; overflow-wrap: anywhere; margin: 0; }
/* ── tables ── */
@@ -39,16 +39,21 @@ export async function stopEngine() {
const ok = await confirmDialog({
title: 'Fermare il motore?',
body: open
? `${open === 1 ? 'Il basket aperto resta' : `I ${open} basket aperti restano`} sul conto con gli stop nativi finché il motore non riparte (salvo «Chiudi i basket alla fermata» in Impostazioni ▸ Esecuzione).`
? `${open === 1 ? 'Il basket aperto resta' : `I ${open} basket aperti restano`} sul conto con gli stop nativi finché il motore non riparte (salvo «Chiudi i basket all'arresto» in Impostazioni ▸ Esecuzione).`
: 'Nessun basket aperto. Il motore si ferma e non apre niente finché non lo riavvii.',
okText: 'Ferma'
});
if (ok) report(await command('stop'));
}
/** Kill-switch: closes every bot position and blocks entries until a reset. */
/**
* Kill-switch: closes every bot position and blocks entries until a reset. The box for the foreign
* positions starts as risk.closeForeignOnKill says, and the choice made here is always sent
* explicitly: it is what happens (the setting is only the default, and what Telegram and the console use).
*/
export async function killSwitch() {
const foreign = t().foreignPositions || 0;
const byDefault = t().closeForeignOnKill === true;
const r = await confirmDialog({
title: 'Kill-switch',
danger: true,
@@ -56,10 +61,14 @@ export async function killSwitch() {
body: el('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } },
el('p', null, 'Annulla gli ordini pendenti, chiude tutte le posizioni del bot (basket, gambe in attesa, orfane) e blocca le nuove entrate fino a un ripristino.'),
el('p', { class: 'small' }, 'Niente viene dichiarato chiuso senza rilettura del conto: se resta qualcosa lo stato diventa «bloccato con residuo».')),
check: { label: foreign ? `Chiudi anche ${foreign === 1 ? 'la posizione ESTERNA (non aperta dal bot)' : `le ${foreign} posizioni ESTERNE (non aperte dal bot)`}` : 'Chiudi anche le posizioni ESTERNE (ora non ce ne sono)', checked: false }
check: {
label: foreign ? `Chiudi anche ${foreign === 1 ? 'la posizione ESTERNA (non aperta dal bot)' : `le ${foreign} posizioni ESTERNE (non aperte dal bot)`}` : 'Chiudi anche le posizioni ESTERNE (ora non ce ne sono)',
checked: byDefault,
hint: byDefault ? 'Accesa perché in Impostazioni ▸ Strategia «Il kill-switch chiude anche le posizioni esterne» è attivo: spegnila per lasciarle aperte.' : ''
}
});
if (!r) return;
const res = await command('kill', { foreign: r.checked });
const res = await command('kill', { foreign: r.checked === true });
if (!res.ok) { report(res); return; }
const left = res.data?.positions || [];
if (left.length) notice(`${res.data.message || 'Kill-switch eseguito.'}\nAncora sul conto: ${left.map(p => `${p.positionId} ${p.symbol || ''}`.trim()).join(', ')}.`, 'warn', 'Kill-switch con residuo');
@@ -3,7 +3,7 @@
// POST /api/commands/<name>. Pages are static ES modules; only the visible one is in the DOM and
// renders, coalesced in requestAnimationFrame. Live operations always ask for CONFERMO LIVE.
import { el, $, setText, setTitle, setClass, setHidden, money, moneyTip, pct, num, sgn, dur, hm, store, isNum, api, pl } from './util.js';
import { el, $, setText, setTitle, setClass, setHidden, money, moneyTip, pct, num, sgn, dur, hm, store, isNum, api, pl, nextUtcMidnight, heartbeatLimits } from './util.js';
import { state, subscribe, onRender, scheduleRender } from './state.js';
import { startStream } from './stream.js';
import { icon } from './icons.js';
@@ -171,13 +171,23 @@ function engineText(t) {
if (a.paused) bits.push('entrate in pausa');
if (a.entriesBlockedReason) bits.push('entrate bloccate: ' + a.entriesBlockedReason);
if (isNum(t.engineTickAgeSeconds) && t.state === 'running') bits.push('ultimo ciclo ' + dur(t.engineTickAgeSeconds) + ' fa');
const hb = t.health?.heartbeatAgeSeconds;
if (isNum(hb) && t.state === 'running') {
const lim = heartbeatLimits(t.heartbeatSeconds);
bits.push(`heartbeat ${dur(hb)} fa (ogni ${dur(lim.every)})` + (hb > lim.bad ? ': in ritardo, il controllo di salute del container lo considera fermo' : ''));
}
return bits.join(' · ');
}
/** The heartbeat is late for its own interval: /api/health answers ok:false. */
function heartbeatLate(t) {
const hb = t.health?.heartbeatAgeSeconds;
return t.state === 'running' && isNum(hb) && hb > heartbeatLimits(t.heartbeatSeconds).bad;
}
function engineDot(t) {
const a = t.alarms || {};
if (t.state === 'faulted' || a.halted) return 'bad';
if (t.state === 'starting' || t.state === 'stopping') return 'warn';
if (t.state === 'running') return a.paused || a.entriesBlockedReason || a.recoveryPending || a.dailyLossHit || a.unreconciled ? 'warn' : '';
if (t.state === 'running') return a.paused || a.entriesBlockedReason || a.recoveryPending || a.dailyLossHit || t.dailyLossLatched || a.unreconciled || heartbeatLate(t) ? 'warn' : '';
return 'off';
}
@@ -239,7 +249,8 @@ function alarmList(t) {
// A first start: nothing in the secret store, so no engine can start until the keys are saved.
if (t.health?.secrets === 'empty' && t.state !== 'running' && t.state !== 'starting') list.push({ lvl: 'warn', pill: 'SENZA CHIAVI', text: 'Nessuna chiave eToro salvata: il motore non può partire. Inseriscile in Impostazioni ▸ Conto, poi premi AVVIA.', act: ['Apri impostazioni', () => go('impostazioni')] });
if (a.unreconciled) list.push({ lvl: 'warn', pill: 'NON RICONCILIATO', text: 'Posizioni non riconciliate: ' + (a.unreconciledReason || '—'), act: ['Posizioni', () => go('posizioni')] });
if (a.dailyLossHit) list.push({ lvl: 'warn', pill: 'PERDITA GIORNALIERA', text: `Perdita giornaliera oltre la soglia del ${pct(t.dailyLossPct)}: nessuna nuova entrata fino a mezzanotte UTC.` });
// D-52: once hit, the block holds until 00:00 UTC (dailyLossLatched) even if equity recovers.
if (a.dailyLossHit || t.dailyLossLatched) list.push({ lvl: 'warn', pill: 'PERDITA GIORNALIERA', text: `Perdita giornaliera oltre la soglia del ${pct(t.dailyLossPct)}: nessuna nuova entrata fino alle 00:00 UTC (${hm(nextUtcMidnight())} nel tuo fuso)` + (t.dailyLossLatched ? ', anche se l\'equity recupera.' : '.') });
if (a.entriesBlockedReason) list.push({ lvl: 'warn', pill: 'ENTRATE BLOCCATE', text: `Entrate bloccate: ${a.entriesBlockedReason}${a.entriesBlockedUntilUtc ? ' fino alle ' + hm(a.entriesBlockedUntilUtc) : ''}. Le uscite restano attive.` });
if (a.paused) list.push({ lvl: 'warn', pill: 'PAUSA', text: 'Entrate in pausa per scelta dell\'operatore; le uscite restano attive.', act: ['Riprendi', () => actions.pauseEntries(false)] });
if (a.recoveryPending) list.push({ lvl: 'warn', pill: 'RECUPERO', text: 'Recupero dopo inattività in corso: entrate bloccate finché le serie non sono riscaldate.' });
@@ -3,6 +3,7 @@
import { el, setText, setTitle, setClass, num, isNum, minutes, hm, now } from './util.js';
import { flags } from './flags.js';
import { reasons, humanize } from './labels.js';
export const STATES = {
Idle: ['Inattivo', 'faint', 'Nessuna posizione: il bot valuta l\'ingresso a ogni chiusura di barra'],
@@ -16,10 +17,18 @@ export const STATES = {
Error: ['Errore', 'bad', 'Errore: vedi il log'],
Disabled: ['Disabilitato', 'faint', 'Basket disabilitato']
};
/**
* The server's word wins: a switched-off basket still in PendingB, Error or Exiting has exposure on the
* account and must say so. Only an idle switched-off basket reads «Disabilitato» (older servers send
* Idle there instead of Disabled).
*/
export function stateOf(b) {
const s = b.enabled === false && b.state !== 'Open' ? STATES.Disabled : STATES[b.state] || [b.state, '', ''];
return { text: s[0], cls: s[1], tip: s[2] };
const s = b.enabled === false && b.state === 'Idle' ? STATES.Disabled : STATES[b.state] || [b.state, '', ''];
const off = b.enabled === false && b.state !== 'Disabled' && b.state !== 'Idle';
return { text: s[0], cls: s[1], tip: s[2] + (off ? ' · basket disabilitato: niente nuove entrate, la posizione resta seguita fino alla chiusura' : '') };
}
/** A row is dimmed only when the basket is switched off and holds nothing on the account. */
export const dimmed = b => b.enabled === false && !b.isOpen && (b.state === 'Disabled' || b.state === 'Idle' || b.state === 'Closed');
export const sideText = side => side === 'buy' ? 'compra' : side === 'sell' ? 'vende' : '—';
export const sideTip = side => side === 'buy' ? 'Cross comprato: entrambe le gambe comprate' : side === 'sell' ? 'Cross venduto: entrambe le gambe vendute' : 'Nessuna posizione';
export function pml(b) {
@@ -67,12 +76,16 @@ export function nameCell(td, b, isNew) {
}
setText(td._b, b.name);
setText(td._x, b.cross);
setTitle(td, `${b.name}: gambe ${b.pairA} e ${b.pairB}, cross sintetico ${b.cross}` + (b.enabled === false ? ' · disabilitato' : '') + (b.intent ? ' · ' + b.intent : ''));
setTitle(td, `${b.name}: gambe ${b.pairA} e ${b.pairB}, cross sintetico ${b.cross}` + (b.enabled === false ? ' · disabilitato' : '') + (b.intent ? ' · ' + humanize(b.intent) : ''));
}
/** «nessun segnale, cost gate (no_signal, cost_gate)»: the words and the ledger's codes. */
export function codesText(codes) {
return codes && codes.length ? `${reasons(codes)} (${codes.join(', ')})` : '';
}
export function stateCell(td, b, isNew) {
if (isNew) { td._t = el('span', { class: 'tag' }); td.replaceChildren(td._t); }
const s = stateOf(b);
setText(td._t, s.text);
setClass(td._t, 'tag ' + s.cls);
setTitle(td, s.tip + (b.intent ? ' · ' + b.intent : '') + (b.reasonCodes && b.reasonCodes.length ? ' · codici: ' + b.reasonCodes.join(', ') : ''));
setTitle(td, s.tip + (b.intent ? ' · ' + humanize(b.intent) : '') + (b.reasonCodes && b.reasonCodes.length ? ' · motivi: ' + codesText(b.reasonCodes) : ''));
}
@@ -53,7 +53,10 @@ export function modal({ title, content, buttons = [{ text: 'Chiudi', value: null
back.addEventListener('mousedown', e => { if (e.target === back && dismissable) close(null); });
document.addEventListener('keydown', onKey, true);
document.body.append(back);
(box.querySelector('input:not([type="checkbox"]),select,textarea') || footer.lastChild)?.focus();
// A text field takes the focus. Otherwise the last button, except when it is destructive: then
// «Annulla» (the first), so a held or repeated Enter never runs a kill-switch or a close.
const safe = buttons.some(b => b.kind === 'danger') ? footer.firstChild : footer.lastChild;
(box.querySelector('input:not([type="checkbox"]),select,textarea') || safe)?.focus();
onOpen?.(box, close, footer);
});
}
@@ -75,7 +78,10 @@ export function report(res, { important = false, title } = {}) {
else if (important && msg) notice(msg, 'ok', title);
}
/** Yes/no, optionally with a checkbox: returns { checked } when confirmed, null otherwise. */
/**
* Yes/no, optionally with a checkbox ({ label, checked, hint }): returns { checked } when confirmed,
* null otherwise. The hint is a short line under the box (where its default comes from).
*/
export async function confirmDialog({ title, body, okText = 'Conferma', danger = false, check, wide }) {
let box = null;
const content = el('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px' } },
@@ -84,6 +90,7 @@ export async function confirmDialog({ title, body, okText = 'Conferma', danger =
box = el('input', { type: 'checkbox' });
box.checked = !!check.checked;
content.append(el('label', { class: 'check' }, box, el('span', null, check.label)));
if (check.hint) content.append(el('div', { class: 'hint' }, check.hint));
}
const v = await modal({ title, content, wide, buttons: [{ text: 'Annulla', value: false }, { text: okText, kind: danger ? 'danger' : 'primary', value: true }] });
return v === true ? { checked: box ? box.checked : false } : null;
@@ -9,6 +9,7 @@ const paths = {
history: '<path d="M4 12a8 8 0 1 0 2.4-5.7L4 8.5"/><path d="M4 4v4.5h4.5"/><path d="M12 8v4.5l3 2"/>',
chart: '<path d="M4 19h16"/><path d="M6.5 15l4-5 3 3 4.5-6"/>',
log: '<path d="M6 3.5h9l3.5 3.5v13.5H6z"/><path d="M9 11h6M9 14.5h6M9 18h4"/>',
list: '<path d="M9 6.5h11M9 12h11M9 17.5h11"/><path d="M4.5 6.5h.01M4.5 12h.01M4.5 17.5h.01"/>',
system: '<rect x="3.5" y="4" width="17" height="7" rx="1.5"/><rect x="3.5" y="13" width="17" height="7" rx="1.5"/><path d="M7 7.5h.01M7 16.5h.01"/><path d="M11 7.5h6M11 16.5h6"/>',
gear: '<circle cx="12" cy="12" r="3"/><path d="M12 2.5v3M12 18.5v3M4.2 6.2l2.1 2.1M17.7 15.7l2.1 2.1M2.5 12h3M18.5 12h3M4.2 17.8l2.1-2.1M17.7 8.3l2.1-2.1"/>',
power: '<path d="M12 3.5v8"/><path d="M6.6 6.8a7.5 7.5 0 1 0 10.8 0"/>',
@@ -57,9 +58,12 @@ const paths = {
const cache = new Map();
/** icon('power', 'extra-class') → a fresh <svg class="ico …">. Unknown names fall back to "close". */
/**
* icon('power', 'extra-class') → a fresh <svg class="ico …">. An unknown name draws an empty icon:
* never a glyph that means something else (a close X in a section header reads as a control).
*/
export function icon(name, cls = '') {
const key = paths[name] ? name : 'close';
const key = Object.hasOwn(paths, name) ? name : '';
let t = cache.get(key);
if (!t) {
t = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
@@ -70,7 +74,7 @@ export function icon(name, cls = '') {
t.setAttribute('stroke-width', '1.9');
t.setAttribute('stroke-linecap', 'round');
t.setAttribute('stroke-linejoin', 'round');
t.innerHTML = paths[key]; // static markup written above, never data
t.innerHTML = key ? paths[key] : ''; // static markup written above, never data
cache.set(key, t);
}
const s = t.cloneNode(true);
@@ -0,0 +1,162 @@
// Italian words for the tokens the ledger and the engine write (ledger evento, reason codes, exit
// reasons, order states, log sources). The raw token stays in the tooltip: it is what the ledger,
// the CSV exports and the log file contain. An unknown token is shown as it is.
/** Ledger `evento` (decisions.jsonl): the Decisioni tab and the z chart of the Basket page. */
export const EVENTO = {
skip: 'nessun ingresso',
segnale_ingresso: 'segnale d\'ingresso',
ingresso: 'ingresso',
rifiuto: 'rifiuto',
posizione: 'in posizione',
segnale_aggiunta: 'segnale d\'aggiunta',
aggiunta: 'aggiunta',
segnale_uscita: 'segnale d\'uscita',
uscita: 'uscita',
leg_risk_unwind: 'gamba richiusa',
correzione: 'correzione',
pending: 'gamba senza esito',
pending_risolto: 'esito della gamba',
orfana_adottata: 'orfana adottata',
orfana_chiusa: 'orfana chiusa',
movimento_di_cassa: 'movimento di cassa',
margin_guard: 'guardia del margine',
kill_switch_avviato: 'kill-switch avviato',
kill_switch_concluso: 'kill-switch concluso',
residuo_chiuso: 'residuo chiuso',
reset_rifiutato: 'ripristino rifiutato',
reset_concluso: 'ripristino concluso',
recupero_avviato: 'recupero avviato',
recupero_concluso: 'recupero concluso',
comando: 'comando',
configurazione: 'configurazione',
realizzato: 'realizzato',
verifica_realizzato: 'verifica del realizzato',
pnl_realizzato: 'P&L realizzato'
};
/** Reason codes of a decision and exit reasons of a closed basket or leg (docs/LEDGER_SCHEMA.md). */
export const REASON = {
no_signal: 'nessun segnale',
rho_low: 'correlazione debole',
rho_short_low: 'correlazione recente debole',
half_life: 'semiperiodo fuori intervallo',
blackout_before: 'blackout prima di un evento',
blackout_after: 'blackout dopo un evento',
weekend: 'fine settimana',
just_opened: 'mercato appena riaperto',
session: 'fuori dalle fasce orarie',
max_baskets: 'basket massimi aperti',
same_cross: 'stesso cross già aperto',
ml_gate: 'filtro del modello (p_ML)',
cost_gate: 'cost gate',
sizing: 'dimensione non calcolabile',
kill_switch: 'kill-switch',
equity_stop: 'equity stop',
daily_loss: 'perdita giornaliera',
entries_blocked: 'entrate bloccate',
data_quality: 'qualità dei dati',
warmup: 'riscaldamento',
not_bar_close: 'barra non ancora chiusa',
enter: 'ingresso',
add: 'aggiunta',
hold: 'tiene',
tp_pips: 'take-profit',
tp_z: 'rientro dello z-score',
stop_z: 'stop sullo z-score',
stop_max_loss: 'perdita massima del basket',
spread_anomaly: 'spread anomalo',
time_stop: 'time-stop',
rho_break: 'correlazione rotta',
margin: 'margine insufficiente',
margin_guard: 'guardia del margine',
min_exposure: 'esposizione minima non raggiunta',
manual: 'chiusura manuale',
closed_by_broker: 'chiuso da eToro',
leg_closed_by_broker: 'gamba chiusa da eToro',
end_of_data: 'fine dei dati',
leg_risk_unwind: 'gamba richiusa',
orphan_closed: 'orfana chiusa',
bonifica_orfana: 'bonifica dell\'orfana'
};
/** The class that wrote a log line (Log.SourceOf): the area of the bot it belongs to. */
export const SOURCE = {
BasketEngine: 'motore',
BasketExecutor: 'esecuzione',
OrderTracker: 'ordini',
BotSupervisor: 'supervisore',
Program: 'avvio',
HeadlessRunner: 'avvio',
ContextRefresher: 'contesto',
Feeds: 'feed',
HistoryService: 'storico',
Settlements: 'realizzato',
RealizedBackfill: 'realizzato',
Ledger: 'ledger',
LearningState: 'apprendimento',
LearningCycle: 'apprendimento',
SettingsRuntime: 'impostazioni',
SettingsService: 'impostazioni',
EnvironmentImport: 'importazione',
SecretStore: 'segreti',
NotifierHub: 'notifiche',
TelegramNotifier: 'Telegram',
TelegramCommands: 'Telegram',
EtoroBroker: 'eToro',
EtoroHttp: 'eToro',
SnapshotHub: 'interfaccia',
TickWriter: 'interfaccia',
WebHost: 'web',
LogBridge: 'web'
};
/** The state of an order as eToro or the order register reports it. */
export const ORDER_STATUS = {
Sent: 'inviato',
Submitted: 'accettato',
Pending: 'in lavorazione',
Filled: 'eseguito',
Executed: 'eseguito',
Rejected: 'rifiutato',
Cancelled: 'annullato',
Canceled: 'annullato',
Unknown: 'sconosciuto'
};
/** What limited the size of a basket (sizing.bound). */
export const BOUND = { risk: 'rischio', leverage: 'leva massima', margin: 'margine', units: 'unità massime', min_exposure: 'esposizione minima' };
/** The leg of an order or a position. */
export const LEG = { add: 'aggiunta' };
const word = (map, v) => (v == null || v === '' ? '—' : map[v] || String(v));
export const evento = v => word(EVENTO, v);
export const reason = v => word(REASON, v);
export const reasons = list => (list || []).map(reason).join(', ');
export const source = v => (v ? SOURCE[v] || String(v) : '');
export const bound = v => word(BOUND, v);
export const leg = v => (v ? LEG[v] || String(v) : '');
/** «Rejected: insufficient margin» → «rifiutato: insufficient margin». */
export function orderStatus(s) {
if (!s) return '—';
const m = /^([A-Za-z]+)(.*)$/.exec(String(s));
return m && ORDER_STATUS[m[1]] ? ORDER_STATUS[m[1]] + m[2] : String(s);
}
/** «tp_pips (take-profit)» for a tooltip: the word and the ledger's own token. */
export const tip = (label, raw) => (raw && label !== raw ? `${label} (${raw})` : label);
// A snake_case token the maps know, standing alone in a text: after a space, a bracket or a colon,
// before a space, a closing bracket, a comma or the end of a sentence. File names (data_quality.csv)
// and paths (/data/state/x_y.json) never match.
const TOKEN = /(^|[\s([«"':;,])([a-z][a-z0-9]*(?:_[a-z0-9]+)+)(?=$|[\s)\]»"',;:!?]|\.(?:\s|$))/g;
/** The engine's texts (log, intents, motivazioni) with the known tokens in Italian: «motivo tp_pips» → «motivo take-profit». */
export function humanize(text) {
if (text == null) return '';
const t = String(text);
if (t.indexOf('_') < 0) return t;
return t.replace(TOKEN, (all, pre, tok) => {
const l = REASON[tok] || EVENTO[tok];
return l ? pre + l : all;
});
}
@@ -8,6 +8,8 @@ import { Grid } from '../grid.js';
import { icon } from '../icons.js';
import { section, tile, kv, tag, setTag, stacks, markdown } from '../ui.js';
import { weightBars, calibrationPlot, sparkline } from '../charts.js';
import { stateOf, dimmed } from '../baskets.js';
import { reason as exitWord, tip } from '../labels.js';
let ctx, w, d, T, S = {}, G = {}, layout, statusTag, reason, runBtn, warnBox, showAll = false, calDim = '', fxSeen;
const MODE = { 'ombra-disabilitato': ['Disabilitato', '', 'Apprendimento spento (ADR-0006): il modello resta in ombra e non filtra niente'], ombra: ['Ombra', 'acc', 'Il modello calcola p_ML e lo scrive nel ledger, ma non filtra gli ingressi'], attivo: ['Attivo', 'ok', 'Il modello filtra gli ingressi sotto la probabilità minima'] };
@@ -16,11 +18,12 @@ const f2 = v => (isNum(v) ? num(v, 2) : '—');
const okMark = v => (v == null ? '—' : v ? '✓' : '✗');
const okCls = v => (v == null ? 'faint' : v ? 'ok' : 'bad');
function groupGrid(scroller, caption) {
/** A breakdown of the dataset; `word` turns a key into Italian (exit reasons), the raw key stays in the tooltip. */
function groupGrid(scroller, caption, word) {
return new Grid({
scroller, rowKey: r => r.key, compact: true, caption, emptyText: 'Nessun dato',
columns: [
{ key: 'k', label: caption, minPx: 110, text: r => r.key || '—' },
{ key: 'k', label: caption, minPx: 110, text: r => (word ? word(r.key) : r.key || '—'), tip: r => (word ? tip(word(r.key), r.key) : r.key || '—') },
{ key: 'n', label: 'N', width: '48px', cls: 'num', text: r => String(r.count), sort: r => r.count },
{ key: 'wr', label: 'Win rate', width: '70px', cls: 'num', text: r => pct(r.winRate, 0) },
{ key: 'p', label: 'P&L netto', width: '92px', cls: 'num', text: r => money(r.pnlNetUsd, true), klass: r => (r.pnlNetUsd > 0 ? 'pos' : r.pnlNetUsd < 0 ? 'neg' : ''), tip: r => moneyTip(r.pnlNetUsd) + ` · medio ${money(r.meanPnlUsd, true)}` }
@@ -65,9 +68,9 @@ function build(host) {
S.bsk = section('Per basket', { ic: 'basket', body: 'tw' });
G.bsk = new Grid({
scroller: S.bsk.body, rowKey: r => r.basket, compact: true, caption: 'Per basket',
rowClass: r => (r.enabled === false ? 'dim' : ''),
rowClass: r => (dimmed(r) ? 'dim' : ''),
columns: [
{ key: 'b', label: 'Basket', minPx: 120, text: r => r.basket, tip: r => `${r.basket} (${r.cross}) · ${r.state}` },
{ key: 'b', label: 'Basket', minPx: 120, text: r => r.basket, tip: r => `${r.basket} (${r.cross}) · ${stateOf(r).text.toLowerCase()}` },
{ key: 'p', label: 'p_ML', width: '58px', cls: 'num', text: r => (isNum(r.pMl) ? num(r.pMl * 100, 0) + ' %' : '—'), tip: r => (isNum(r.pMl) ? `p_ML ${num(r.pMl, 3)} (${r.pMlKind || '—'}, ${when(r.pMlUtc)})` : 'Nessuna stima') },
{ key: 'f', label: 'Filtro', width: '54px', cls: 'c', text: r => (r.wouldBeFiltered ? 'sì' : '—'), klass: r => (r.wouldBeFiltered ? 'warn' : 'faint'), tip: r => (r.wouldBeFiltered ? 'Con il modello attivo questo ingresso sarebbe filtrato' : 'Passerebbe il filtro') },
{
@@ -110,7 +113,7 @@ function build(host) {
S.dataKv = kv([['closed', 'Basket chiusi'], ['lab', 'Etichettati'], ['noentry', 'Senza riga d\'ingresso'], ['nofeat', 'Senza feature'], ['lone', 'Gambe sole'], ['corr', 'Corretti'], ['unv', 'Non verificati'], ['demo', 'Chiusi in Demo'], ['first', 'Primo'], ['lastc', 'Ultimo'], ['hash', 'Hash', '', true]]);
S.byMode = el('div', { class: 'chips' });
const t1 = el('div', { class: 'tw' }), t2 = el('div', { class: 'tw' }), t3 = el('div', { class: 'tw' });
G.byBasket = groupGrid(t1, 'Basket'); G.byPreset = groupGrid(t2, 'Preset'); G.byExit = groupGrid(t3, 'Uscita');
G.byBasket = groupGrid(t1, 'Basket'); G.byPreset = groupGrid(t2, 'Preset'); G.byExit = groupGrid(t3, 'Uscita', exitWord);
S.data.body.append(S.dataKv.node, S.byMode, el('div', { class: 'card' }, t1), el('div', { class: 'card' }, t2), el('div', { class: 'card' }, t3));
S.cal = section('Calibrazione per fascia', { ic: 'target', body: 'in', sub: 'knowledge/calibration.csv' });
@@ -264,7 +267,9 @@ function render(data) {
T.bandit.sub(`esplorazione ${pct(b.explorationShare, 0)} · ${b.choices ?? 0} scelte`, 'proposta, mai applicata');
const vm = state.tick?.learning?.volModel || d.baskets?.find(x => x.vol)?.vol?.activeModel || '—';
T.vol.set(vm, '');
T.vol.sub(d.volatility ? `storia di ${num(d.volatility.historyCount, 0)} barre` : '—', d.volatility ? `terzili ${num(d.volatility.tercileLow * 1e4, 1)} / ${num(d.volatility.tercileHigh * 1e4, 1)} bp` : '');
// The terciles are unknown (null) below nine closes since the engine started: a dash, never 0,0.
const bp = x => (isNum(x) ? num(x * 1e4, 1) : '—');
T.vol.sub(d.volatility ? `storia di ${num(d.volatility.historyCount, 0)} barre` : '—', d.volatility ? `terzili ${bp(d.volatility.tercileLow)} / ${bp(d.volatility.tercileHigh)} bp` : '');
T.last.set(sc.lastCycleUtc ? when(sc.lastCycleUtc) : 'mai', sc.lastError ? 'neg' : '');
T.last.sub(sc.lastError ? 'errore: ' + sc.lastError : `${sc.lastTrigger || lc?.trigger || '—'} · ${isNum(sc.lastDurationMs) ? dur(sc.lastDurationMs / 1000) : '—'}`, lc ? `versione ${lc.version} · ${lc.rows} righe` : '');
T.next.set(running ? 'in corso' : sc.nextDueUtc ? when(sc.nextDueUtc) : '—', running ? 'warn' : sc.due ? 'warn' : '');
@@ -10,7 +10,8 @@ import { flags } from '../flags.js';
import { verticalSplit } from '../split.js';
import { kv, tag, setTag } from '../ui.js';
import { zGauge, pipsProgress, weightBars } from '../charts.js';
import { nameCell, stateCell, stateOf, sideText, sideTip, pml, pmlTip, eventText, eventTip, eventLabel } from '../baskets.js';
import { nameCell, stateCell, stateOf, sideText, sideTip, pml, pmlTip, eventText, eventTip, eventLabel, dimmed, codesText } from '../baskets.js';
import { evento, reason, bound, humanize, tip } from '../labels.js';
let ctx, grid, sel, detail, poll, learnWatch, learning, counters, head, tabsEl, pane, tab, built, chart;
const TABS = [['stato', 'Stato'], ['posizione', 'Posizione'], ['segnale', 'Segnale'], ['contesto', 'Contesto'], ['ml', 'ML'], ['decisioni', 'Decisioni']];
@@ -23,11 +24,11 @@ function listGrid(scroller) {
return new Grid({
scroller, rowKey: b => b.name, caption: 'Basket',
onSelect: id => select(id, true),
rowClass: b => (b.enabled === false ? 'dim' : ''),
rowClass: b => (dimmed(b) ? 'dim' : ''),
columns: [
{ key: 'name', label: 'Basket', width: '236px', narrow: [[700, '168px'], [480, '150px']], render: nameCell, sig: b => b.name + b.enabled + b.intent, sort: b => b.name },
{ key: 'state', label: 'Stato', width: '90px', render: stateCell, sig: b => b.state + b.enabled + b.intent + (b.reasonCodes || []).join(), sort: b => b.state },
{ key: 'intent', label: 'Intento', minPx: 170, hideBelow: 1180, text: b => b.intent || '—', tip: b => b.intent + (b.reasonCodes?.length ? ' · ' + b.reasonCodes.join(', ') : '') },
{ key: 'intent', label: 'Intento', minPx: 170, hideBelow: 1180, text: b => (b.intent ? humanize(b.intent) : '—'), tip: b => humanize(b.intent) + (b.reasonCodes?.length ? ' · motivi: ' + codesText(b.reasonCodes) : '') },
{ key: 'side', label: 'Verso', width: '60px', hideBelow: 1260, text: b => sideText(b.side), tip: b => sideTip(b.side), klass: b => (b.side === 'buy' ? 'pos' : b.side === 'sell' ? 'neg' : 'faint') },
{
key: 'z', label: 'z', width: '124px', narrow: [640, '96px'], hideBelow: 440, sort: b => (isNum(b.z) ? Math.abs(b.z) : null),
@@ -129,7 +130,7 @@ function zChart() {
const key = pts.map(r => r.atUtc + r.z).join() + '|' + span + '|' + n;
if (dots._key !== key) {
dots._key = key;
dots.replaceChildren(...pts.map((r, i) => dot(x(i), y(r.z), 'zdot' + (Math.abs(r.z) >= zin ? ' hot' : ''), `${when(r.atUtc)} · z ${sgn(r.z, 2)} · ${r.evento}: ${r.motivazione}`)));
dots.replaceChildren(...pts.map((r, i) => dot(x(i), y(r.z), 'zdot' + (Math.abs(r.z) >= zin ? ' hot' : ''), `${when(r.atUtc)} · z ${sgn(r.z, 2)} · ${evento(r.evento)}: ${humanize(r.motivazione)}`)));
}
nowDot.setAttribute('visibility', liveZ == null ? 'hidden' : 'visible');
if (liveZ != null) { for (const [k, v] of [['x1', x(n - 1)], ['x2', x(n - 1)], ['y1', y(liveZ)], ['y2', y(liveZ)]]) nowDot.setAttribute(k, v); nowTip.textContent = `adesso · z ${sgn(liveZ, 2)}`; }
@@ -197,14 +198,14 @@ function tabStato(d) {
});
const b = (state.tick?.baskets || []).find(x => x.name === sel);
const s = b ? stateOf(b) : { cls: '' };
setText(v.verdict, d.intent || (d.enabled ? '—' : 'Disabilitato: ' + (d.disabledReason || '')));
setText(v.verdict, d.intent ? humanize(d.intent) : (d.enabled ? '—' : 'Disabilitato: ' + (d.disabledReason || '')));
setClass(v.verdict, 'verdict ' + (s.cls === 'ok' ? 'ok' : s.cls === 'warn' ? 'warn' : s.cls === 'bad' ? 'bad' : d.enabled === false ? '' : 'acc'));
const ld = d.lastDecision;
const k = ld ? KIND[ld.kind] || [ld.kind, ''] : ['—', ''];
setTag(v.kind, k[0], k[1]);
setText(v.at, ld ? when(ld.atUtc) : 'nessuna decisione registrata');
fill(v.codes, (ld?.reasonCodes || []).join(), () => (ld?.reasonCodes || []).map(c => el('span', { class: 'code-chip' }, c)));
setText(v.why, ld?.motivazione || '');
fill(v.codes, (ld?.reasonCodes || []).join(), () => (ld?.reasonCodes || []).map(c => el('span', { class: 'code-chip', title: tip(reason(c), c) }, reason(c))));
setText(v.why, humanize(ld?.motivazione));
const th = d.thresholds || {}, e = d.eval || {};
const az = isNum(e.z) ? Math.abs(e.z) : null;
@@ -237,7 +238,7 @@ function tabStato(d) {
v.size.set('loss', z ? money(z.lossAtStopUsd) : '—', { title: z ? moneyTip(z.lossAtStopUsd, 'Perdita attesa allo stop') : '' });
v.size.set('lev', z ? num(z.effectiveLeverage, 2) + '×' : '—');
v.size.set('mrg', z ? money(z.marginUsd) : '—');
v.size.set('bound', z?.bound || '—');
v.size.set('bound', z?.bound ? bound(z.bound) : '—', { title: z?.bound ? 'Vincolo: ' + tip(bound(z.bound), z.bound) : '' });
}
function tabPosizione(d) {
@@ -292,7 +293,7 @@ function tabPosizione(d) {
K.set('zd', f2(p.zStopDistance)); K.set('ts', isNum(p.barsToTimeStop) ? String(p.barsToTimeStop) : '—');
K.set('rb', String(p.barsWithBrokenCorrelation), { cls: p.barsWithBrokenCorrelation > 0 ? 'warn' : '' });
K.set('sa', String(p.barsWithSpreadAnomaly), { cls: p.barsWithSpreadAnomaly > 0 ? 'warn' : '' });
K.set('eq', money(p.equityAtEntry)); K.set('why', p.entryMotivazione || '—');
K.set('eq', money(p.equityAtEntry)); K.set('why', p.entryMotivazione ? humanize(p.entryMotivazione) : '—');
v.grid.setRows(p.legs || []);
}
@@ -369,9 +370,9 @@ function tabDecisioni(d) {
scroller: o.w, rowKey: r => r.atUtc + r.evento, compact: true, caption: 'Decisioni', emptyText: 'Nessuna decisione registrata',
columns: [
{ key: 't', label: 'Ora', width: '92px', text: r => when(r.atUtc), tip: r => r.atUtc },
{ key: 'e', label: 'Evento', width: '96px', text: r => r.evento },
{ key: 'e', label: 'Evento', width: '112px', text: r => evento(r.evento), tip: r => tip(evento(r.evento), r.evento) },
{ key: 'z', label: 'z', width: '56px', cls: 'num', text: r => s2(r.z) },
{ key: 'm', label: 'Motivazione', minPx: 160, text: r => r.motivazione }
{ key: 'm', label: 'Motivazione', minPx: 160, text: r => humanize(r.motivazione) }
]
});
pane.replaceChildren(el('p', { class: 'help' }, 'Le ultime 20 decisioni alla chiusura della barra M15, dalla più recente.'), o.w);
@@ -1,17 +1,19 @@
// Dashboard: everything that matters on one screen (no scrolling at 1440×900). KPI tiles, the five
// baskets, the next events, the quotes and the latest log lines. Details live in the other pages.
import { el, setText, setTitle, setClass, setHidden, money, moneyShort, moneyTip, pct, num, sgn, isNum, dur, hms, hm, weekdayHm, until, when, toDate, now } from '../util.js';
import { el, setText, setTitle, setClass, setHidden, money, moneyShort, moneyTip, pct, num, sgn, isNum, dur, hms, hm, weekdayHm, until, when, toDate, now, nextUtcMidnight } from '../util.js';
import { state, subscribe, watch } from '../state.js';
import { Grid } from '../grid.js';
import { icon } from '../icons.js';
import { flag, flags, pairCurrencies } from '../flags.js';
import { section, tile } from '../ui.js';
import { zGauge, pipsProgress } from '../charts.js';
import { nameCell, stateCell, sideText, sideTip, pml, pmlTip, eventText, eventTip } from '../baskets.js';
import { nameCell, stateCell, sideText, sideTip, pml, pmlTip, eventText, eventTip, dimmed } from '../baskets.js';
import { humanize, source } from '../labels.js';
let ctx, grid, tiles, sub, updated, evBody, evRows, mkCells, logList, unsub = [], market, calendar = [];
const LOG_LINES = 60;
/** Lines of the activity strip: logging.statusLines from the tick (Impostazioni ▸ Log), 60 before the first tick. */
const logLines = () => (isNum(state.tick?.statusLines) && state.tick.statusLines > 0 ? state.tick.statusLines : 60);
function buildTiles() {
const T = {
@@ -54,10 +56,17 @@ function renderTiles(t) {
T.dd.sub(`stop a ${pct(t.equityStopPct)}`, `picco ${moneyShort(t.peakEquity)}`);
T.dd.bar(ddr, ddr >= 0.8 ? 'bad' : ddr >= 0.5 ? 'warn' : 'acc');
// D-52: once hit, the block holds until 00:00 UTC even if equity recovers (dailyLossLatched).
const used = t.dailyLossUsedPct;
T.loss.set(pct(used, 0), t.alarms?.dailyLossHit ? 'neg' : used >= 0.6 ? 'warn' : '');
T.loss.sub(`soglia ${pct(t.dailyLossPct)}`, t.alarms?.dailyLossHit ? 'raggiunta' : 'calo da 00:00');
T.loss.bar(used, t.alarms?.dailyLossHit || used >= 1 ? 'bad' : used >= 0.6 ? 'warn' : 'acc');
const latched = t.dailyLossLatched === true;
const hit = latched || t.alarms?.dailyLossHit === true;
T.loss.set(pct(used, 0), hit ? 'neg' : used >= 0.6 ? 'warn' : '',
'Quanto della soglia di perdita giornaliera è consumato (calo dell\'equity netta da mezzanotte UTC, cassa esclusa). '
+ (latched ? `Soglia raggiunta: l'apertura di nuovi basket è bloccata fino alle 00:00 UTC (${hm(nextUtcMidnight())} nel tuo fuso), anche se l'equity recupera; le uscite restano attive.`
: hit ? 'Soglia raggiunta: niente nuove entrate; le uscite restano attive.'
: 'Alla soglia niente nuove entrate fino alle 00:00 UTC.'));
T.loss.sub(`soglia ${pct(t.dailyLossPct)}`, latched ? `blocco fino ${hm(nextUtcMidnight())}` : hit ? 'raggiunta' : 'calo da 00:00');
T.loss.bar(used, hit || used >= 1 ? 'bad' : used >= 0.6 ? 'warn' : 'acc');
T.margin.set(money(t.usedMargin), isNum(t.marginRatio) && t.marginRatio < 1.5 ? 'neg' : '', 'Margine usato. ' + moneyTip(t.usedMargin) + ` · disponibile ${money(t.availableBalance)}`);
T.margin.sub(`disp. ${moneyShort(t.availableBalance)}`, `eq/margine ${isNum(t.marginRatio) ? num(t.marginRatio, 1) : '—'}`);
@@ -86,7 +95,7 @@ function basketGrid(scroller) {
return new Grid({
scroller, rowKey: b => b.name, caption: 'Basket',
onSelect: id => ctx.go('basket', { name: id }),
rowClass: b => (b.enabled === false ? 'dim' : ''),
rowClass: b => (dimmed(b) ? 'dim' : ''),
columns: [
{ key: 'name', label: 'Basket', width: '238px', narrow: [[760, '168px'], [480, '150px']], render: nameCell, sig: b => b.name + b.enabled + b.intent },
{ key: 'state', label: 'Stato', width: '92px', render: stateCell, sig: b => b.state + b.enabled + b.intent + (b.reasonCodes || []).join() },
@@ -168,28 +177,42 @@ function renderQuotes(t) {
}
q.forEach((x, i) => {
const c = mkCells.cells[i];
const ratio = isNum(x.spreadMedianPips) && x.spreadMedianPips > 0 ? x.spreadPips / x.spreadMedianPips : null;
// Just after AVVIA a symbol is listed before its first quote: bid, ask and spread are null.
const quoted = isNum(x.bid) && isNum(x.ask);
const ratio = isNum(x.spreadPips) && isNum(x.spreadMedianPips) && x.spreadMedianPips > 0 ? x.spreadPips / x.spreadMedianPips : null;
const d = /JPY/.test(x.symbol) ? 3 : 5;
setText(c.mid, num((x.bid + x.ask) / 2, d));
setText(c.mid, quoted ? num((x.bid + x.ask) / 2, d) : '—');
setText(c.sp, num(x.spreadPips, 1));
setClass(c.sp, ratio == null ? '' : ratio > 2 ? 'neg' : ratio > 1.3 ? 'warn' : 'pos');
setText(c.r, ratio == null ? '' : num(ratio, 1) + '×');
setTitle(c.node, `${x.symbol}: bid ${num(x.bid, d)} · ask ${num(x.ask, d)} · spread ${num(x.spreadPips, 2)} pip` + (isNum(x.spreadMedianPips) ? ` · mediana 24 h ${num(x.spreadMedianPips, 2)} pip (${num(ratio, 2)}×)` : '') + (isNum(x.ageSeconds) ? ` · quotazione di ${dur(x.ageSeconds)} fa` : ''));
setTitle(c.node, !quoted ? `${x.symbol}: nessuna quotazione ancora (in attesa della prima lettura)`
: `${x.symbol}: bid ${num(x.bid, d)} · ask ${num(x.ask, d)} · spread ${num(x.spreadPips, 2)} pip` + (isNum(x.spreadMedianPips) ? ` · mediana 24 h ${num(x.spreadMedianPips, 2)} pip` + (ratio == null ? '' : ` (${num(ratio, 2)}×)`) : '') + (isNum(x.ageSeconds) ? ` · quotazione di ${dur(x.ageSeconds)} fa` : ''));
});
}
// ── log strip ───────────────────────────────────────────────────────────────────────────────────
const LEVEL = { error: 'ERROR', warn: 'WARN', info: 'INFO', debug: 'DEBUG', trace: 'TRACE' };
const shownInStrip = e => e.level !== 'trace' && e.level !== 'debug';
function logRow(e) {
return el('div', { class: 'lr ' + e.level, title: `${hms(e.timeUtc)} · ${e.level} · ${e.source || ''}\n${e.message}` },
el('span', { class: 't' }, hms(e.timeUtc)), el('span', { class: 'lvl ' + e.level }, LEVEL[e.level] || e.level), el('span', { class: 'm' }, e.message));
return el('div', { class: 'lr ' + e.level, title: `${hms(e.timeUtc)} · ${e.level} · ${source(e.source)}${e.source ? ` (${e.source})` : ''}\n${e.message}` },
el('span', { class: 't' }, hms(e.timeUtc)), el('span', { class: 'lvl ' + e.level }, LEVEL[e.level] || e.level), el('span', { class: 'm' }, humanize(e.message)));
}
function trimLog() {
const n = logLines();
while (logList.childElementCount > n) logList.lastChild.remove();
}
function appendLog(list) {
const nodes = list.filter(e => e.level !== 'trace' && e.level !== 'debug').map(logRow).reverse();
const nodes = list.filter(shownInStrip).map(logRow).reverse();
if (!nodes.length) return;
logList.querySelector('.empty')?.remove();
logList.prepend(...nodes);
while (logList.childElementCount > LOG_LINES) logList.lastChild.remove();
trimLog();
}
/** The last `logLines()` lines the strip shows (debug and trace excluded), oldest first. */
function recentLines() {
const n = logLines(), out = [];
for (let i = state.events.length - 1; i >= 0 && out.length < n; i--) if (shownInStrip(state.events[i])) out.push(state.events[i]);
return out.reverse();
}
export default {
@@ -216,7 +239,7 @@ export default {
reg.body.addEventListener('click', () => ctx.go('log'));
host.append(el('div', { class: 'body' }, kpis, bsk.node, side, reg.node));
appendLog(state.events.slice(-LOG_LINES));
appendLog(recentLines());
unsub.push(subscribe('events', appendLog));
unsub.push(subscribe('events-reset', () => logList.replaceChildren(el('div', { class: 'empty' }, 'Nessuna riga'))));
market = watch({ key: 'market', url: '/api/market?calendarDays=7&impact=High,Medium&news=0', every: 60000, onData: d => { calendar = d?.calendar?.events || []; evBody._key = null; if (state.tick) renderEvents(state.tick); } });
@@ -234,6 +257,7 @@ export default {
grid.setRows(t.baskets || []);
renderEvents(t);
renderQuotes(t);
if (logList.childElementCount > logLines()) trimLog(); // statusLines lowered in Impostazioni
const bits = [];
bits.push(t.state === 'running' ? `In esecuzione da ${dur(t.uptimeSeconds)}` : { stopped: 'Motore fermo', starting: 'Avvio…', stopping: 'Arresto…', faulted: 'Motore in errore' }[t.state] || t.state);
if (t.state === 'running' && isNum(t.engineTickAgeSeconds)) bits.push(`ultimo ciclo ${dur(t.engineTickAgeSeconds)} fa`);
@@ -53,7 +53,7 @@ function fieldRow(f) {
ctl = el('label', { class: 'switch' }, input, el('span'));
get = () => (input.checked ? 'true' : 'false');
set = v => { input.checked = v === 'true'; };
input.addEventListener('change', () => changed(f));
input.addEventListener('change', () => changed(f.path));
if (f.readOnly) input.disabled = true;
} else if (f.kind === 'choice') {
const s = el('select', { class: 'txt', 'aria-label': f.label }, (f.options || []).map(o => el('option', { value: o }, o)));
@@ -65,7 +65,7 @@ function fieldRow(f) {
s.addEventListener('change', () => {
if (fl) fill(fl, s.value, () => flag(s.value) || []);
if (f.path === 'ui.theme') document.documentElement.dataset.theme = s.value === 'light' ? 'light' : 'dark';
changed(f);
changed(f.path);
});
if (isCur) s.title = 'Valuta con cui l\'interfaccia mostra gli importi: ' + (f.options || []).map(o => `${o} ${COUNTRY[o] || ''}`.trim()).join(', ');
if (f.readOnly) s.disabled = true;
@@ -78,7 +78,7 @@ function fieldRow(f) {
ctl = f.suffix && f.suffix.length <= INNER_SUFFIX ? el('span', { class: 'withsuf' }, input, el('span', { class: 'suf' }, f.suffix)) : input;
get = () => input.value;
set = v => { input.value = v; };
input.addEventListener('input', () => changed(f));
input.addEventListener('input', () => changed(f.path));
if (f.readOnly) input.readOnly = true;
}
const outer = f.suffix && f.suffix.length > INNER_SUFFIX && f.kind !== 'bool' && f.kind !== 'choice' ? el('span', { class: 'u' }, f.suffix) : null;
@@ -90,18 +90,26 @@ function fieldRow(f) {
return ui;
}
function changed(f) {
const ui = fields.get(f.path);
const text = ui.get();
const orig = shown(f, f.value);
if (text === orig) { dirty.delete(f.path); clearResult(ui); }
else {
const r = f.kind === 'bool' || f.kind === 'choice' ? { value: text } : wire(f, text);
if (r.error) { dirty.set(f.path, { error: r.error }); showResult(ui, 'error', r.error, true); }
else { dirty.set(f.path, { value: r.value }); clearResult(ui); }
}
ui.node.classList.toggle('dirty', dirty.has(f.path));
ui.input.classList?.toggle('invalid', !!dirty.get(f.path)?.error);
/**
* What the text of a field means against the value the server has now: null when unchanged,
* { value } to send, { error } to show. `f` must be the current descriptor (ui.f, replaced at every
* reload and after every save), never the one a row was built with: after two saves of a field the
* build-time value is stale, and going back to it would look unchanged and could not be saved.
*/
export function editOf(f, text) {
if (text === shown(f, f.value)) return null;
return f.kind === 'bool' || f.kind === 'choice' ? { value: text } : wire(f, text);
}
function changed(path) {
const ui = fields.get(path);
if (!ui) return;
const r = editOf(ui.f, ui.get());
if (!r) { dirty.delete(path); clearResult(ui); }
else if (r.error) { dirty.set(path, { error: r.error }); showResult(ui, 'error', r.error, true); }
else { dirty.set(path, { value: r.value }); clearResult(ui); }
ui.node.classList.toggle('dirty', dirty.has(path));
ui.input.classList?.toggle('invalid', !!dirty.get(path)?.error);
syncButtons();
}
function syncButtons() {
@@ -282,7 +290,10 @@ function refreshValues(d) {
const ui = fields.get(f.path);
if (!ui) continue;
ui.f = f;
if (dirty.has(f.path) || document.activeElement === ui.input) continue;
// An edit in progress is kept (with the error the server gave it, if any); it stops being an
// edit only when the server now holds what was typed (saved elsewhere).
if (dirty.has(f.path)) { if (!editOf(f, ui.get())) changed(f.path); continue; }
if (document.activeElement === ui.input) continue;
ui.set(shown(f, f.value));
if (f.error) showResult(ui, 'error', f.error, true);
}
@@ -1,10 +1,12 @@
// Log: one line per message (time in the browser zone, coloured level tag, source, message with
// ellipsis; a click opens the full text). Lines arrive with the tick (append-only by seq); a filter
// change reloads from /api/log. At most 2000 rows stay in the DOM.
// change reloads from /api/log. At most 2000 rows stay in the DOM. The source and the ledger's
// tokens in the message are shown in Italian; the tooltip and the CSV keep the text of the log file.
import { el, setText, setTitle, hms, dateTime, api, debounce, store, download, csvLine } from '../util.js';
import { state, subscribe } from '../state.js';
import { icon } from '../icons.js';
import { source, humanize } from '../labels.js';
const MAX_ROWS = 2000;
const RANK = { trace: 0, debug: 1, info: 2, warn: 3, error: 4 };
@@ -12,6 +14,7 @@ const MIN = { tutti: 0, info: 2, warn: 3, error: 4 };
const LABEL = { error: 'ERROR', warn: 'WARN', info: 'INFO', debug: 'DEBUG', trace: 'TRACE' };
let list, level, search, follow, followBox, count, fileNote, rows = [], lastSeq = 0, unsub = null, seq = 0;
/** Same rule as the server's `q` (the text of the log file), so loaded and streamed lines agree. */
function matches(e) {
if ((RANK[e.level] ?? 2) < (MIN[level.value] ?? 0)) return false;
const q = search.value.trim().toLowerCase();
@@ -21,8 +24,8 @@ function row(e) {
return el('div', { class: 'lr ' + e.level, dataset: { seq: e.seq }, title: e.message },
el('span', { class: 't', title: dateTime(e.timeUtc) }, hms(e.timeUtc)),
el('span', { class: 'lvl ' + e.level }, LABEL[e.level] || e.level),
el('span', { class: 'src' }, e.source || ''),
el('span', { class: 'm' }, e.message));
el('span', { class: 'src', title: e.source || null }, source(e.source)),
el('span', { class: 'm' }, humanize(e.message)));
}
function atBottom() { return list.scrollTop + list.clientHeight >= list.scrollHeight - 40; }
function scrollEnd() { requestAnimationFrame(() => { list.scrollTop = list.scrollHeight; }); }
@@ -74,7 +77,7 @@ export default {
level = el('select', { class: 'txt', title: 'Livello minimo', 'aria-label': 'Livello minimo' },
el('option', { value: 'tutti' }, 'Tutti i livelli'), el('option', { value: 'info' }, 'Info e oltre'), el('option', { value: 'warn' }, 'Warning ed errori'), el('option', { value: 'error' }, 'Solo errori'));
level.value = store.get('log.level', 'tutti');
search = el('input', { class: 'txt', type: 'search', placeholder: 'Cerca…', 'aria-label': 'Cerca nel log', style: { width: '240px' } });
search = el('input', { class: 'txt', type: 'search', placeholder: 'Cerca…', 'aria-label': 'Cerca nel log', title: 'Cerca nel testo del file di log: le sorgenti e i codici come li scrive il bot (BasketEngine, tp_pips), visibili nel tooltip di ogni riga', style: { width: '240px' } });
follow = el('input', { type: 'checkbox' });
follow.checked = store.get('log.follow', true);
followBox = el('label', { class: 'chk' + (follow.checked ? ' on' : ''), title: 'Segui: con la vista in fondo, le righe nuove la fanno scorrere' }, el('span', { class: 'switch' }, follow, el('span')), 'Segui');
@@ -2,8 +2,8 @@
// calendar (filters by impact and currency), sentiment per currency, the latest news and the
// volatility forecast per basket. Read from /api/market when its version changes.
import { el, setText, setTitle, setClass, setHidden, num, sgn, isNum, dur, when, weekdayHm, until, dateTime, hm, store, fill, displayCurrency } from '../util.js';
import { watch } from '../state.js';
import { el, setText, setTitle, setClass, setHidden, num, sgn, isNum, dur, when, weekdayHm, until, dateTime, hm, hms, store, fill, displayCurrency, now, toDate } from '../util.js';
import { state, watch } from '../state.js';
import { Grid } from '../grid.js';
import { icon } from '../icons.js';
import { flag, flags, pairCurrencies, COUNTRY } from '../flags.js';
@@ -30,7 +30,7 @@ function quotesGrid(s) {
{ key: 'sp', label: 'Spread', width: '62px', cls: 'num', text: r => num(r.spreadPips, 1), tip: r => `Spread ${num(r.spreadPips, 2)} pip`, sort: r => r.spreadPips },
{ key: 'med', label: 'Mediana 24 h', width: '92px', cls: 'num', hideBelow: 560, text: r => (isNum(r.spreadMedian24hPips) ? num(r.spreadMedian24hPips, 1) : '—') },
{ key: 'ratio', label: 'Rapporto', width: '72px', cls: 'num', text: r => (isNum(r.spreadRatio) ? num(r.spreadRatio, 2) + '×' : '—'), klass: r => (r.spreadRatio > 2 ? 'neg' : r.spreadRatio > 1.3 ? 'warn' : r.spreadRatio != null ? 'pos' : ''), tip: () => 'Spread attuale sulla mediana delle ultime 24 h: oltre 2× niente ingressi, oltre 3× chiusura forzata', sort: r => r.spreadRatio },
{ key: 'age', label: 'Età', width: '58px', cls: 'num', hideBelow: 640, text: r => dur(r.ageSeconds), klass: r => (r.ageSeconds > 30 ? 'warn' : ''), tip: r => 'Quotazione delle ' + dateTime(r.quoteUtc) + (r.realtime ? ' · tempo reale' : ' · ritardata') },
{ key: 'age', label: 'Età', width: '58px', cls: 'num', hideBelow: 640, text: r => dur(r.ageSeconds), klass: r => (r.ageSeconds > 30 ? 'warn' : ''), tip: r => (isNum(r.ageSeconds) ? `Letta dal bot ${dur(r.ageSeconds)} fa` : 'Mai quotato') + (r.quoteUtc ? ' · quotazione eToro delle ' + dateTime(r.quoteUtc) : '') + (r.realtime ? ' · tempo reale' : ' · ritardata') + (r.live ? ' · aggiornata dal flusso ogni secondo' : '') },
{ key: 'atr', label: 'ATR', width: '56px', cls: 'num', hideBelow: 720, text: r => (isNum(r.atrPips) ? num(r.atrPips, 1) : '—'), tip: () => 'Average True Range su M15, in pip' },
{ key: 'used', label: 'Usato da', minPx: 120, hideBelow: 820, text: r => (r.conversionOnly ? 'solo conversione' : (r.usedBy || []).join(', ') || '—') }
]
@@ -77,7 +77,9 @@ function buildFilters() {
filters = store.get('mercato.cal', { impact: ['High', 'Medium'], ccy: [] });
const box = el('div', { class: 'fchips' });
const draw = () => {
const ccys = [...new Set((data?.calendar?.events || []).map(e => e.currency))].filter(Boolean).sort();
// A remembered currency always has its chip, even in a week without its events: the filter
// that hides the calendar must stay visible and can be switched off.
const ccys = [...new Set([...(data?.calendar?.events || []).map(e => e.currency), ...filters.ccy])].filter(Boolean).sort();
box.replaceChildren(
...['High', 'Medium', 'Low', 'Holiday'].map(k => chip(IMPACT[k][0], k, filters.impact.includes(k), () => { toggle(filters.impact, k); draw(); renderCalendar(); }, [el('span', { class: 'dot sm ' + IMPACT[k][1] }), IMPACT[k][0]])),
el('span', { class: 'tool-sep' }),
@@ -148,16 +150,44 @@ function renderNews(d) {
setText(secs.news.sub, `${items.length} · ${d.news?.state || '—'}` + (d.news?.updatedUtc ? ' · ' + when(d.news.updatedUtc) : ''));
}
/**
* The quotes as of now. The section is rebuilt at most every 15 s and read again on a bar close, so
* its bid, ask, spread and age would stay frozen: the basket instruments take them from the tick
* (fresh every second), the conversion-only pairs age with the clock from the section's time.
*/
function liveQuotes(t) {
const rows = data?.quotes || [];
const tq = new Map((t?.quotes || []).map(q => [q.symbol, q]));
const asOf = toDate(data?.asOfUtc);
const elapsed = asOf ? Math.max(0, (now() - asOf.getTime()) / 1000) : 0;
return rows.map(r => {
const q = tq.get(r.symbol);
if (q) {
const spread = isNum(q.spreadPips) ? q.spreadPips : r.spreadPips;
const median = isNum(r.spreadMedian24hPips) ? r.spreadMedian24hPips : q.spreadMedianPips;
return { ...r, live: true,
bid: isNum(q.bid) ? q.bid : r.bid, ask: isNum(q.ask) ? q.ask : r.ask, spreadPips: spread,
spreadRatio: isNum(spread) && isNum(median) && median > 0 ? spread / median : r.spreadRatio,
ageSeconds: isNum(q.ageSeconds) ? q.ageSeconds : isNum(r.ageSeconds) ? r.ageSeconds + elapsed : null };
}
return isNum(r.ageSeconds) ? { ...r, ageSeconds: r.ageSeconds + elapsed } : r;
});
}
function renderQuotes(t) {
grids.q.setRows(liveQuotes(t));
const live = (t?.quotes || []).length > 0;
setText(secs.q.sub, `${(data?.quotes || []).length} strumenti · ` + (live && t?.nowUtc ? `aggiornato ${hms(t.nowUtc)}` : hm(data?.asOfUtc)));
}
function render(d) {
data = d;
grids.q.setRows(d.quotes || []);
renderQuotes(state.tick);
grids.fx.setRows(d.fx || []);
grids.vol.setRows(d.volatility || []);
fbox._draw();
renderCalendar();
renderSentiment(d);
renderNews(d);
setText(secs.q.sub, `${(d.quotes || []).length} strumenti · ${hm(d.asOfUtc)}`);
if (!render.done) { render.done = true; requestAnimationFrame(() => layout?.relayout()); }
}
@@ -186,7 +216,9 @@ export default {
w = watch({ key: 'market', url: '/api/market?calendarDays=7&impact=High,Medium,Low,Holiday&news=50', onData: render });
},
unmount() { w?.stop(); layout?.disconnect(); for (const g of Object.values(grids)) g.destroy(); grids = {}; secs = {}; w = layout = null; data = null; },
render() {
if (data && grids.cal) for (const [, tr] of grids.cal.trs) { const td = tr.children[3]; const r = grids.cal.rows.get(tr.dataset.id); if (r) setText(td, until(r.timeUtc)); }
render(t) {
if (!data) return;
if (grids.q) renderQuotes(t);
if (grids.cal) for (const [, tr] of grids.cal.trs) { const td = tr.children[3]; const r = grids.cal.rows.get(tr.dataset.id); if (r) setText(td, until(r.timeUtc)); }
}
};
@@ -8,6 +8,7 @@ import { Grid } from '../grid.js';
import { icon } from '../icons.js';
import { flags, pairCurrencies } from '../flags.js';
import { section, tile } from '../ui.js';
import { leg, orderStatus, tip } from '../labels.js';
let ctx, data, w, posGrid, ordGrid, tiles, problem, counters, bonifica, srcNote, fxSeen;
const ORIGIN = { basket: ['basket', 'acc', 'Aperta da un basket del bot'], 'orfana-bot': ['orfana del bot', 'bad', 'Posizione del bot senza il suo basket: viene adottata e chiusa'], esterna: ['esterna', 'faint', 'Non aperta dal bot: mai toccata'] };
@@ -30,7 +31,7 @@ function positionsGrid(scroller) {
rowClass: r => (r.origin === 'esterna' ? 'dim' : ''),
columns: [
{ key: 'origin', label: 'Origine', width: '104px', narrow: [700, '92px'], render: originCell, sig: r => r.origin + r.reason, sort: r => r.origin },
{ key: 'basket', label: 'Basket · gamba', minPx: 130, text: r => (r.basket ? `${r.basket}${r.leg ? ' · ' + r.leg : ''}` : '—'), tip: r => (r.basketId ? `${r.basket} (${r.basketId}) gamba ${r.leg || '—'}` : r.reason || 'Nessun basket'), sort: r => r.basket },
{ key: 'basket', label: 'Basket · gamba', minPx: 130, text: r => (r.basket ? `${r.basket}${r.leg ? ' · ' + leg(r.leg) : ''}` : '—'), tip: r => (r.basketId ? `${r.basket} (${r.basketId}) gamba ${r.leg ? leg(r.leg) : '—'}` : r.reason || 'Nessun basket'), sort: r => r.basket },
{ key: 'sym', label: 'Strumento', width: '112px', render: symCell, sig: r => r.symbol, sort: r => r.symbol },
{ key: 'side', label: 'Verso', width: '58px', hideBelow: 600, text: r => r.side, klass: r => (r.side === 'long' ? 'pos' : 'neg') },
{ key: 'units', label: 'Unità', width: '84px', cls: 'num', hideBelow: 640, text: r => num(r.units, 0), tip: r => `${num(r.units, 2)} unità · esposizione ${money(r.exposureUsd)}`, sort: r => r.units },
@@ -62,12 +63,12 @@ function ordersGrid(scroller) {
scroller, rowKey: r => r.clientRef || r.orderId, caption: 'Ordini in attesa', emptyText: 'Nessun ordine in attesa di esito', compact: true,
columns: [
{ key: 'basket', label: 'Basket', minPx: 140, text: r => r.basket || '—', tip: r => r.basketId },
{ key: 'leg', label: 'Gamba', width: '60px', text: r => r.leg || '—' },
{ key: 'leg', label: 'Gamba', width: '68px', text: r => (r.leg ? leg(r.leg) : '—') },
{ key: 'sym', label: 'Strumento', width: '112px', render: symCell, sig: r => r.symbol },
{ key: 'side', label: 'Verso', width: '64px', hideBelow: 700, text: r => (r.side === 'buy' ? 'compra' : 'vende'), klass: r => (r.side === 'buy' ? 'pos' : 'neg') },
{ key: 'u', label: 'Unità', width: '84px', cls: 'num', hideBelow: 640, text: r => num(r.requestedUnits, 0) },
{ key: 'oid', label: 'Ordine', width: '96px', cls: 'num m', hideBelow: 760, text: r => String(r.orderId || '—') },
{ key: 'st', label: 'Ultimo stato', minPx: 110, text: r => r.lastStatus || '—' },
{ key: 'st', label: 'Ultimo stato', minPx: 110, text: r => orderStatus(r.lastStatus), tip: r => tip(orderStatus(r.lastStatus), r.lastStatus) },
{ key: 'chk', label: 'Letture', width: '64px', cls: 'num', hideBelow: 820, text: r => String(r.checks), tip: () => 'Quante volte l\'esito è stato letto per orderId' },
{ key: 'age', label: 'Età', width: '72px', cls: 'num', text: r => dur(r.ageSeconds), klass: r => (r.ageSeconds > 60 ? 'warn' : ''), tip: r => 'Inviato ' + dateTime(r.sentUtc) + ' · rif. ' + r.clientRef }
]
@@ -2,7 +2,7 @@
// feeds, Telegram, secrets, process, disk, log, web, diagnostics and about. /api/system is read
// every 3 s while the page is visible (304 when nothing changed).
import { el, setText, setTitle, setClass, setHidden, num, sgn, pct, isNum, dur, when, ago, dateTime, bytes, api, fill } from '../util.js';
import { el, setText, setTitle, setClass, setHidden, num, sgn, pct, isNum, dur, when, ago, dateTime, bytes, api, fill, heartbeatLimits } from '../util.js';
import { state, watch, command } from '../state.js';
import { Grid } from '../grid.js';
import { icon } from '../icons.js';
@@ -12,11 +12,12 @@ import { confirmDialog, promptDialog, report, notice } from '../dialog.js';
let ctx, w, d, S = {}, K = {}, G = {}, layout, pauseBtn, locked;
const yes = v => (v ? 'sì' : 'no');
const ORPHANS = { Close: 'adottate e chiuse', Report: 'solo segnalate' };
function build(body) {
S.eng = section('Motore', { ic: 'power', body: 'in' });
K.eng = kv([['state', 'Stato'], ['acc', 'Conto'], ['preset', 'Preset'], ['start', 'Avviato'], ['up', 'In esecuzione da'], ['tick', 'Ultimo ciclo', 'da quanto il ciclo di decisione non gira'], ['hb', 'Heartbeat', 'ultimo battito scritto in data/state/heartbeat.json'],
['rec', 'Recupero dopo inattività'], ['blk', 'Entrate bloccate'], ['pause', 'Pausa dell\'operatore'], ['auto', 'Avvio automatico'], ['orph', 'Orfane', 'Close = adottate e chiuse; Report = solo segnalate'], ['lock', 'Istanza', 'instance.lock: un solo bot per cartella dati'], ['run', 'Run id', '', true], ['hash', 'Hash della strategia', '', true]]);
['rec', 'Recupero dopo inattività'], ['blk', 'Entrate bloccate'], ['pause', 'Pausa dell\'operatore'], ['auto', 'Avvio automatico'], ['orph', 'Orfane del bot', 'Close = adottate e chiuse alla riconciliazione; Report = solo segnalate'], ['lock', 'Istanza', 'instance.lock: un solo bot per cartella dati'], ['run', 'Run id', '', true], ['hash', 'Hash della strategia', '', true]]);
pauseBtn = el('button', { class: 'btn', type: 'button', onclick: () => ctx.actions.pauseEntries(!d?.engine?.paused) }, icon('pause'), el('span', null, 'Pausa'));
S.eng.body.append(K.eng.node, el('div', { class: 'row' }, pauseBtn, el('button', { class: 'btn', type: 'button', title: 'Procedura in cinque passi dopo un kill-switch o un equity stop', onclick: () => ctx.actions.resetWizard() }, icon('undo'), 'Ripristino…')));
@@ -147,10 +148,18 @@ function render(data) {
K.eng.set('acc', e.account === 'live' ? 'REALE (Live)' : 'demo', { cls: e.account === 'live' ? 'bad' : '' });
K.eng.set('preset', e.preset); K.eng.set('start', e.startedUtc ? dateTime(e.startedUtc) : '—'); K.eng.set('up', e.startedUtc ? dur(e.uptimeSeconds) : '—');
K.eng.set('tick', isNum(e.tickAgeSeconds) ? dur(e.tickAgeSeconds) + ' fa' : '—', { cls: e.tickAgeSeconds > 10 ? 'warn' : '' });
K.eng.set('hb', isNum(e.heartbeatAgeSeconds) ? dur(e.heartbeatAgeSeconds) + ' fa' : '—', { cls: e.heartbeatAgeSeconds > 105 ? 'bad' : e.heartbeatAgeSeconds > 60 ? 'warn' : '' });
// Judged against its own interval (Impostazioni ▸ Strategia ▸ «Heartbeat ogni»), never a fixed 105 s:
// the server's threshold of /api/health when it gives one, otherwise three beats plus 15 s.
const hb = heartbeatLimits(e.heartbeatSeconds > 0 ? e.heartbeatSeconds : state.tick?.heartbeatSeconds);
const stale = e.heartbeatStaleSeconds > 0 ? e.heartbeatStaleSeconds : hb.bad;
K.eng.set('hb', isNum(e.heartbeatAgeSeconds) ? `${dur(e.heartbeatAgeSeconds)} fa · ogni ${dur(hb.every)}` : '—', {
cls: e.heartbeatAgeSeconds > stale ? 'bad' : e.heartbeatAgeSeconds > hb.warn ? 'warn' : '',
title: `Ultimo battito scritto in data/state/heartbeat.json: ${isNum(e.heartbeatAgeSeconds) ? dur(e.heartbeatAgeSeconds) + ' fa' : '—'}. Il motore lo scrive ogni ${hb.every} s; oltre ${stale} s il controllo di salute del container lo considera fermo.`
});
K.eng.set('rec', e.recoveryPending ? 'in corso' + (e.recoveryCause ? ': ' + e.recoveryCause : '') : 'no', { cls: e.recoveryPending ? 'warn' : '' });
K.eng.set('blk', e.entriesBlockedReason ? e.entriesBlockedReason + (e.entriesBlockedUntilUtc ? ' fino ' + when(e.entriesBlockedUntilUtc) : '') : 'no', { cls: e.entriesBlockedReason ? 'warn' : '' });
K.eng.set('pause', yes(e.paused), { cls: e.paused ? 'warn' : '' }); K.eng.set('auto', yes(e.autostart)); K.eng.set('orph', e.orphanPolicy); K.eng.set('lock', e.instanceLock || '—');
K.eng.set('pause', yes(e.paused), { cls: e.paused ? 'warn' : '' }); K.eng.set('auto', yes(e.autostart));
K.eng.set('orph', ORPHANS[e.orphanPolicy] || e.orphanPolicy, { title: `Orfane del bot: ${ORPHANS[e.orphanPolicy] || e.orphanPolicy} (${e.orphanPolicy || '—'})` }); K.eng.set('lock', e.instanceLock || '—');
K.eng.set('run', e.runId, { cls: 'mono' }); K.eng.set('hash', e.strategyHash, { cls: 'mono' });
if (pauseBtn._p !== !!e.paused) {
pauseBtn._p = !!e.paused;
@@ -8,8 +8,9 @@ import { Grid } from '../grid.js';
import { icon } from '../icons.js';
import { flags, pairCurrencies } from '../flags.js';
import { section, safeSvg } from '../ui.js';
import { reason, orderStatus, humanize, tip } from '../labels.js';
let view, w, grid, content, filterBox, counter, problem, eqBox, seg, fxSeen, tbend, f = {};
let view, w, grid, content, filterBox, counter, problem, eqBox, seg, fxSeen, tbend, filterSig = null, f = {};
const VIEWS = [['ordini', 'Ordini'], ['posizioni', 'Posizioni'], ['periodi', 'Profitti per periodo']];
const RES = { Filled: ['eseguito', 'ok'], Pending: ['in attesa', 'warn'], Rejected: ['rifiutato', 'bad'], Cancelled: ['annullato', 'faint'] };
const ORIGIN = { basket: ['basket', 'acc'], 'orfana-bot': ['orfana del bot', 'bad'], esterna: ['esterna', 'faint'], 'movimento di cassa': ['cassa', 'gold'] };
@@ -42,7 +43,7 @@ const COLS = {
{ key: 'rp', label: 'Prezzo rich.', width: '84px', cls: 'num', hideBelow: 1000, text: r => (r.requestedPrice ? num(r.requestedPrice, dec(r.symbol)) : '—') },
{ key: 'fp', label: 'Prezzo eseg.', width: '84px', cls: 'num', hideBelow: 700, text: r => (r.fillRate ? num(r.fillRate, dec(r.symbol)) : '—') },
{ key: 'sl', label: 'Slippage', width: '70px', cls: 'num', hideBelow: 820, text: r => (isNum(r.slippagePips) ? sgn(r.slippagePips, 1) : '—'), klass: r => (r.slippagePips > 0.5 ? 'warn' : '') },
{ key: 'st', label: 'Stato', width: '96px', hideBelow: 1100, text: r => r.status || '—' },
{ key: 'st', label: 'Stato', width: '96px', hideBelow: 1100, text: r => orderStatus(r.status), tip: r => tip(orderStatus(r.status), r.status) },
{ key: 'res', label: 'Esito', width: '92px', render: (td, r, n) => resTag(td, r, n, r.resolution), sig: r => r.resolution, sort: r => r.resolution },
{ key: 'oid', label: 'Ordine', width: '92px', cls: 'num m', hideBelow: 1180, text: r => (r.orderId ? String(r.orderId) : '—') },
{ key: 'pid', label: 'Posizione', width: '100px', cls: 'num m', hideBelow: 1260, text: r => (r.positionId ? String(r.positionId) : '—') },
@@ -61,7 +62,7 @@ const COLS = {
{ key: 'net', label: 'P&L netto', width: '96px', cls: 'num', text: r => money(r.pnlNetUsd, true), klass: r => signedCls(r.pnlNetUsd), tip: r => moneyTip(r.pnlNetUsd, 'Netto (netProfit − fee) dallo storico eToro'), sort: r => r.pnlNetUsd },
{ key: 'pips', label: 'Pip', width: '60px', cls: 'num', hideBelow: 760, text: r => (isNum(r.pips) ? sgn(r.pips, 1) : '—'), klass: r => signedCls(r.pips) },
{ key: 'dur', label: 'Durata', width: '76px', cls: 'num', hideBelow: 1120, text: r => (r.origin === 'movimento di cassa' ? '—' : dur((r.durationMinutes || 0) * 60)), sort: r => r.durationMinutes },
{ key: 'why', label: 'Motivo', minPx: 120, hideBelow: 700, text: r => r.exitReason || '—' }
{ key: 'why', label: 'Motivo', minPx: 120, hideBelow: 700, text: r => reason(r.exitReason), tip: r => (r.exitReason ? tip(reason(r.exitReason), r.exitReason) : '') }
],
periodi: [
{ key: 'p', label: 'Periodo', minPx: 120, text: r => r.periodo, tip: r => `dal ${dateTime(r.fromUtc)} al ${dateTime(r.toUtc)}` },
@@ -94,7 +95,10 @@ function query(forCsv) {
}
function select(name, options, value, title) {
const s = el('select', { class: 'txt', title, 'aria-label': title }, options.map(([v, t]) => el('option', { value: v }, t)));
// A remembered filter the list does not know (a basket switched off, the engine stopped, an older
// instrument) is still an option: the select shows what filters the table, and «Tutti» clears it.
const opts = value && !options.some(([v]) => v === value) ? [...options, [value, value]] : options;
const s = el('select', { class: 'txt', title, 'aria-label': title }, opts.map(([v, t]) => el('option', { value: v }, t)));
s.value = value || '';
s.addEventListener('change', () => { f[name] = s.value; store.set('storico.f', f); reload(); });
return s;
@@ -104,9 +108,18 @@ function date(name, label) {
i.addEventListener('change', () => { f[name] = i.value; store.set('storico.f', f); reload(); });
return el('label', { class: 'inl' }, label, i);
}
/** The baskets and their legs, from the tick (the quotes are empty while the engine is stopped). */
function filterLists(t) {
const list = t?.baskets || [];
const symbols = new Set();
for (const b of list) { if (b.pairA) symbols.add(b.pairA); if (b.pairB) symbols.add(b.pairB); }
for (const q of t?.quotes || []) symbols.add(q.symbol);
return { baskets: list.map(b => b.name), symbols: [...symbols].sort() };
}
const signature = t => { const l = filterLists(t); return l.baskets.join() + '|' + l.symbols.join(); };
function buildFilters() {
const baskets = (state.tick?.baskets || []).map(b => b.name);
const symbols = [...new Set((state.tick?.quotes || []).map(q => q.symbol))];
const { baskets, symbols } = filterLists(state.tick);
filterSig = signature(state.tick);
const parts = [];
if (view === 'ordini') {
parts.push(select('basket', [['', 'Tutti i basket'], ...baskets.map(b => [b, b])], f.basket, 'Basket'),
@@ -142,7 +155,7 @@ function setView(v) {
grid = new Grid({ scroller, columns: COLS[view], rowKey: KEY[view], storeKey: 'storico.' + view, virtualizeOver: 150, emptyText: 'Nessuna riga nel periodo', rowClass: r => (r.isOpen ? 'dim' : '') });
grid.tbody.addEventListener('mouseover', e => {
const tr = e.target.closest('tr[data-id]');
if (tr && !tr.title) { const r = grid.rows.get(tr.dataset.id); if (r?.motivazione) tr.title = r.motivazione; }
if (tr && !tr.title) { const r = grid.rows.get(tr.dataset.id); if (r?.motivazione) tr.title = humanize(r.motivazione); }
});
w?.stop();
w = watch({ key: 'history', url: () => query(false), every: 60000, onData: render });
@@ -180,6 +193,11 @@ export default {
setView(params?.get('vista') || store.get('storico.tab', 'ordini'));
},
params(p) { const v = p.get('vista'); if (v && v !== view) setView(v); },
unmount() { w?.stop(); grid?.destroy(); w = grid = null; },
render() { if (grid && fxSeen && fxSeen !== fxKey()) { fxSeen = fxKey(); grid.touch(); } }
unmount() { w?.stop(); grid?.destroy(); w = grid = null; filterSig = null; },
render(t) {
// Loaded directly on #/storico the page mounts before the first tick: the basket and instrument
// lists arrive with it (and change when the strategy's baskets change).
if (filterBox && signature(t) !== filterSig) buildFilters();
if (grid && fxSeen && fxSeen !== fxKey()) { fxSeen = fxKey(); grid.touch(); }
}
};
@@ -108,7 +108,8 @@ function ingestEvents(t) {
if (!loaded) { // first tick: the recent past from /api/log, then the delta
loaded = true;
parked.push(...ev);
backfill(0, 300);
// enough for the dashboard's strip (logging.statusLines), within what the store keeps
backfill(0, Math.min(MAX_EVENTS, Math.max(300, typeof t.statusLines === 'number' ? t.statusLines : 0)));
return;
}
if ((ev.length && ev[0].seq > state.lastSeq + 1) || (!ev.length && t.eventsSeq > state.lastSeq)) {
@@ -176,6 +176,19 @@ export function until(v) {
return s > 0 ? 'tra ' + dur(s) : dur(-s) + ' fa';
}
export function minutes(m) { return isNum(m) ? (m >= 0 ? 'tra ' + dur(m * 60) : dur(-m * 60) + ' fa') : '—'; }
/** The next 00:00 UTC (the end of the daily-loss block), as a Date: hm() shows it in the browser's zone. */
export function nextUtcMidnight() {
const d = new Date(now());
return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() + 1));
}
/**
* How old the engine's heartbeat may get: it is written every `every` seconds (tick.heartbeatSeconds,
* 30 when unknown); /api/health calls the engine stuck past three beats plus 15 s.
*/
export function heartbeatLimits(every) {
const s = isNum(every) && every > 0 ? every : 30;
return { every: s, warn: 2 * s, bad: 3 * s + 15 };
}
// ── amounts: USD from the server, display currency in the browser ──────────────────────────────
const SYMBOL = { USD: '$', EUR: '€', GBP: '£', CHF: 'CHF', JPY: '¥', AUD: 'A$', CAD: 'C$', NZD: 'NZ$' };
@@ -252,10 +265,12 @@ export async function track(promise) {
/**
* One call to the bot. Returns { ok, status, data, etag, notModified }; never throws for HTTP
* errors (network failures give status 0). A 401 sends the browser to the login page.
* Every call that changes state (any method but GET/HEAD) says Content-Type: application/json, with
* or without a body: the server refuses the others (415), so a cross-site form cannot post here.
*/
export async function api(path, { method = 'GET', body, etag, quiet = false } = {}) {
const headers = { Accept: 'application/json' };
if (body !== undefined) headers['Content-Type'] = 'application/json';
if (body !== undefined || (method !== 'GET' && method !== 'HEAD')) headers['Content-Type'] = 'application/json';
if (etag) headers['If-None-Match'] = etag;
const run = async () => {
let r;