Fix the defects of the Phase 5 review (refs #41 #42 #43 #44 #45 #46)
ci / test (postgres) (push) Successful in 3m52s
ci / test (sqlite) (push) Failing after 2m41s
ci / image (push) Skipped

An independent review found these, now fixed and tested:

- Risk limits could be raised through PUT /api/settings without the
  phrase and the password. The API now refuses risk keys.
- The reference equity counted results twice after reduced to real and
  after a demotion. Each ledger now keeps a baseline, and carried results
  stay in the ledger's currency until the reference is computed.
- An instrument could be bought by a second strategy in the same account
  (SPEC 8.6), and purchases under way did not hold their cash, so several
  purchases sent together could exceed it. Both are refused or shrunk now.
- After an automatic trip of the switch there was no way to restart from
  the interface. Rischio now shows the trip of both worlds and the restart.
- The fresh password of SPEC 12.4 could be tried without limit. Five wrong
  attempts in 15 minutes now lock it.
- Observation to simulation skipped the 90 days of live signals.
- A new build changed the qualification of a strategy with real money,
  "Ferma tutto" counted as a critical incident, raising risk ignored
  demotion conditions in progress, and weekends counted as stock sessions.
- The 12.4 confirmation now summarises capital, first purchases and limits,
  and live strategies show the gap with their simulated twin.

The backtest converts each bar with the rate fixed before it opens, the
day before, and the report now counts how often correctives and risk
changed a decision. crypto_trend is still not passed: the broad universe
now falls 32.8%. The outcome file also keeps the qualified parameters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 16:48:41 +01:00
1 parent 17d6b8db38
commit 9ac159a7db
27 files changed
+1015 -532

No files matched your search

+1 -1
View File
@@ -171,7 +171,7 @@ Le tre strategie di base dentro un motore del rischio che nessuno può aggirare.
- [x] Ogni regola di 9.1 e 9.2 ha il suo test (`RiskTests` e `RiskEngineTests`: perdita del giorno, della settimana, calo dal massimo a 10 e 15%, capitale investito, posizione singola, quota crypto, rischio della singola operazione, controlli tecnici, niente vendite allo scoperto, protezione per le operazioni in giornata, avviso all'80%, ordini al minuto, file STOP; più `NoRuleEverEnlargesWhatTheStrategyAsked` e `AfterALossNoPurchaseIsLarger` come test di proprietà)
- [x] Un test dimostra che senza la procedura di 12.4 nessun ordine raggiunge un conto reale (`NoOrderReachesARealAccountWithoutTheProcedure`)
- [x] Un test dimostra che una strategia retrocessa continua a gestire uscite e stop delle sue posizioni reali fino a zero (`ADemotedStrategyKeepsManagingItsRealPositionsDownToZero`)
- [x] Per ciascuna strategia un rapporto di backtest onesto in `docs/backtests/` (costi doppi e tripli, confronto con comprare e tenere), qualunque sia l'esito, più il file versionato con l'esito per il primo avvio — `crypto_trend` **non superato** (calo del 29,1% sull'universo largo, PBO 0,84 su BTC, ETH e SOL): resta in osservazione (ADR 0011, punto 13). `EveryBaseStrategyHasItsOutcomeFileBuiltIn`, `TheProtocolRunsBothUniversesAndWritesTheReportWhateverTheOutcome`
- [x] Per ciascuna strategia un rapporto di backtest onesto in `docs/backtests/` (costi doppi e tripli, confronto con comprare e tenere), qualunque sia l'esito, più il file versionato con l'esito per il primo avvio — `crypto_trend` **non superato** (calo del 32,8% sull'universo largo, PBO 0,84 su BTC, ETH e SOL): resta in osservazione (ADR 0011, punto 13). `EveryBaseStrategyHasItsOutcomeFileBuiltIn`, `TheProtocolRunsBothUniversesAndWritesTheReportWhateverTheOutcome`
- [x] Senza chiavi Alpaca i backtest azionari restano in attesa dell'utente e le due strategie azionarie restano in osservazione (`AtTheFirstStartTheStockStrategiesWaitInObservationAndCryptoFollowsItsOutcome`; i due rapporti azionari dicono cosa manca)
- [x] I test anti-sguardo-avanti passano (`CryptoTrendDoesNotLookAhead`, `EquityMomentumDoesNotLookAhead`, `EquityMeanrevDoesNotLookAhead`)
- [x] Le schermate Strategie, Rischio e Operazioni corrispondono ai mockup (`TheDemoShowsTradesStrategiesAndRiskAsInTheMockups` e confronto a 1440 e 375 px con i mockup 03, 04 e 07)
+2 -1
View File
@@ -75,7 +75,7 @@ Aggiornato: 2026-11-11
- Correttivi comuni (regime crypto, calendario economico), dimensionamento sulla quota del bot e motore del rischio completo: limiti di perdita per mondo, calo dal massimo con dimezzamento e interruttore, limiti di dimensione, controlli tecnici, niente vendite allo scoperto né leva. Toglie o riduce, mai aggiunge. Gira anche dentro i backtest.
- Ogni passo di una decisione resta scritto con i suoi codici motivo (tabella `decisions`).
- Stadi verso i soldi veri: osservazione, simulazione, reale ridotto, reale. Senza la procedura di 12.4 nessun ordine raggiunge un conto reale; una strategia retrocessa gestisce le uscite delle posizioni reali fino a zero; il gemello simulato resta fuori dai totali. In simulazione entra solo una strategia che ha superato il backtest.
- Backtest onesti in `docs/backtests/` con `anubis backtest base`: storico Binance convertito in euro con il cambio BCE, monete tolte dal listino comprese, due universi, costi doppi e tripli, comprare e tenere accanto. **`crypto_trend` non supera** (calo massimo del 29,1% contro il 25% ammesso; probabilità di sovra-adattamento 0,84 su BTC, ETH e SOL) e resta in osservazione. Le due azionarie aspettano le chiavi di Alpaca. Gli esiti sono inclusi nell'applicazione e letti a ogni avvio.
- Backtest onesti in `docs/backtests/` con `anubis backtest base`: storico Binance convertito in euro con il cambio BCE, monete tolte dal listino comprese, due universi, costi doppi e tripli, comprare e tenere accanto. **`crypto_trend` non supera** (calo massimo del 32,8% contro il 25% ammesso; probabilità di sovra-adattamento 0,84 su BTC, ETH e SOL) e resta in osservazione. Le due azionarie aspettano le chiavi di Alpaca. Gli esiti sono inclusi nell'applicazione e letti a ogni avvio.
- Schermate Operazioni (con la scheda "perché" e l'esportazione CSV), Strategie e Rischio come i mockup 03, 04 e 07; in Impostazioni limiti, protezione per le operazioni in giornata e scenari. Fermare, chiudere e ripartire passano dal motore del rischio; alzare un limite mentre una strategia usa soldi veri chiede frase e password.
## In corso
@@ -97,6 +97,7 @@ Fase 6, motore dal vivo in simulazione: l'orchestrazione della giornata, il proc
- OKX: WebSocket sulla porta 443, la 8443 è chiusa (API-NOTES O3).
- Le coppie in EUR di OKX esistono da novembre 2023: prima di allora la storia crypto viene dagli archivi Binance in USDT. Il Laboratorio li usa nella loro valuta (ADR 0010, punto 13); i backtest delle strategie di base li convertono in euro con il cambio BCE del giorno (ADR 0011, punto 10).
- `crypto_trend` resta in osservazione perché il suo backtest non è superato. Non ho ritoccato regole o soglie dopo aver visto il risultato: una nuova versione della strategia è una nuova prova, che il DSR conterà insieme alle precedenti.
- Il motore dal vivo (Fase 6) deve far girare una strategia con i parametri scritti nel suo file dell'esito (`parameters`), non con quelli predefiniti: sono quelli che si sono qualificati.
- Per rifare i backtest di base: `anubis backtest base --to AAAA-MM-GG --out docs/backtests` (con `--offline` usa gli archivi già scaricati).
- Nella modalità dimostrativa il Laboratorio è spento: mostra l'elenco ma non esegue prove.
- I dati di mercato si spengono con `ANUBIS_MARKET_DATA=off`; nella modalità dimostrativa sono sempre spenti.
+21 -4
View File
@@ -33,13 +33,25 @@ La Fase 5 porta le tre strategie di base, i correttivi comuni, il motore del ris
**5. Ogni passo di una decisione resta scritto.** La nuova tabella `decisions` tiene una riga per passo (strategia, correttivi, dimensionamento, rischio, ordine) con codici motivo e numeri usati. La scheda "perché" di Operazioni collega decisioni ed esecuzioni con l'id d'ordine deterministico (`ClientOrderIds.Key(decision_id)`) e scrive le frasi da modelli italiani fissi.
**6. Gli stadi sono l'unica strada verso i soldi veri.**
- Quattro stadi: osservazione, simulazione, reale ridotto, reale.
- Quattro stadi: osservazione, simulazione, reale ridotto, reale. Da osservazione a simulazione servono il backtest superato e almeno 90 giorni di segnali raccolti dal vivo (12.3); solo il primo avvio porta in simulazione una strategia di base che ha superato il backtest, come dice la specifica.
- Un ordine su un conto reale richiede il consenso della configurazione d'avvio, tutti i requisiti di 12.3 soddisfatti, la frase scritta a mano e password (più il secondo fattore, se attivo) inseriti da poco. I gestori degli ordini sui conti reali, in caso di dubbio, rifiutano e richiedono la conferma prima di ogni ordine.
- Da osservazione a simulazione si passa con un pulsante, ma solo se il backtest della strategia è superato (`Qualification.Passed`). Una strategia che non lo ha superato resta in osservazione e la schermata dice perché.
- Da osservazione a simulazione si passa con un pulsante, ma il libro degli stadi ricontrolla i due requisiti: una strategia che non li ha resta in osservazione e la schermata dice perché.
- La password inserita per la procedura conta i tentativi come l'accesso: dopo cinque errori in 15 minuti è rifiutata anche quella giusta, finché la finestra non passa.
- Prima della conferma la schermata riassume cosa cambia: capitale usato, acquisti del primo ciclo (stimati da ciò che la simulazione tiene in quel momento), limiti e la loro base. Per una strategia con soldi veri mostra la differenza di risultato con il gemello simulato, in percentuale del capitale usato.
- Con soldi veri in gioco l'esito del backtest con cui la strategia si è qualificata non cambia, nemmeno con un aggiornamento del programma: lo riceve quando torna in simulazione. L'esito tiene anche i parametri della variante qualificata, che sono quelli che girano dal vivo (Fase 6).
- Una strategia retrocessa o revocata tiene le posizioni reali in sola uscita, con i loro stop, fino a zero.
- Il gemello simulato di una strategia con soldi veri resta fuori dai totali e dal patrimonio di riferimento.
- Il patrimonio di riferimento è il capitale affidato più i risultati, contati una volta sola. A ogni cambio di stadio il registro che la strategia lascia porta con sé ciò che ha prodotto da quando era in uso (per quattro se viene dal reale ridotto), e il registro che prende il suo posto parte da ciò che ha in quel momento. Così il passaggio da reale ridotto a reale, sullo stesso conto, e il ritorno al gemello dopo una retrocessione non contano due volte gli stessi guadagni. Gli importi restano nella valuta del registro e diventano euro al momento del calcolo.
- Nel calcolo della retrocessione per il percorso atteso le azioni non contano i fine settimana, in cui non ci sono sedute.
**7. Alzare il rischio costa la stessa conferma.** Abbassare un limite è sempre permesso. Alzare un limite o il capitale affidato mentre una strategia usa soldi veri chiede la frase di conferma (`RaisePhrase`) e la password, come la procedura di 12.4. Ogni cambio finisce nel registro delle impostazioni.
**7. Alzare il rischio costa la stessa conferma.** Abbassare un limite è sempre permesso. Alzare un limite o il capitale affidato mentre una strategia usa soldi veri chiede la frase di conferma (`RaisePhrase`) e la password, come la procedura di 12.4. Non passa comunque finché una strategia con soldi veri ha una condizione di retrocessione in corso (12.4). Ogni cambio finisce nel registro delle impostazioni. I limiti non si cambiano dall'API generale delle impostazioni (`PUT /api/settings`): solo dal modulo di Impostazioni, che fa questi controlli.
**7 bis. Liquidità, strumenti e fermate.**
- Un acquisto in corso tiene impegnata la sua liquidità finché non è eseguito, e ogni acquisto conta al prezzo più alto a cui il suo limite può arrivare (la distanza ammessa dall'ultimo prezzo): più acquisti inviati insieme non superano la liquidità della strategia.
- In uno stesso conto uno strumento appartiene a una sola strategia alla volta (8.6): se un'altra lo tiene, o lo sta comprando, l'ingresso salta con il suo motivo.
- "Ferma tutto", il file `STOP` e l'anomalia di ordini al minuto sono eventi di gravità alta, non critici: sono il bot che fa il suo lavoro, non un controllo perso, e non bloccano per 30 giorni il passaggio di stadio (12.3).
- Quando l'interruttore scatta da solo in un mondo, il bot resta "attivo" per l'altro: la pagina Rischio mostra lo scatto di entrambi i mondi e il pulsante "Riparti" anche in questo caso. La ripartenza toglie lo scatto e lascia una pausa com'era.
- Nella pagina Rischio peso di una posizione, quota crypto e rischio di un'operazione si misurano sul patrimonio di riferimento, come nel motore del rischio.
**8. Gli scenari sono una somma semplice.** "Se succedesse domani" applica la variazione al valore delle posizioni del momento. "Con gli stop" prende per ogni posizione la perdita più piccola tra lo scenario e la distanza dal suo stop, arrotondata a 5 € e scritta come "circa", perché uno stop non garantisce il prezzo. Lo scenario del dollaro tocca il conto in dollari e gli stop non lo riducono.
@@ -49,6 +61,7 @@ La Fase 5 porta le tre strategie di base, i correttivi comuni, il motore del ris
- Le barre giornaliere USDT si dividono per il cambio BCE EUR/USD dello stesso giorno, o dell'ultimo precedente fino a 7 giorni prima; altrimenti la barra si scarta. Si salvano come sede `binance_eur`.
- Una serie si ferma al primo buco più lungo di 7 giorni (`MaxGapDays`): ciò che segue è un'altra moneta. Il LUNA rilanciato nel 2022 non si confonde con quello crollato, che si taglia al 13/05/2022.
- L'elenco degli archivi comprende le monete tolte dal listino (49 coppie, con LUNA, FTT, BCC, VEN, XMR…): l'universo passato non è scelto tra i sopravvissuti.
- Ogni barra usa l'ultimo cambio fissato prima della sua apertura, cioè quello del giorno prima: il cambio del giorno d è fissato alle 16:00, dopo l'apertura della barra di d alle 00:00 UTC, e il backtest esegue all'apertura.
- `anubis backtest base --offline` scarica i cambi BCE solo se il file manca.
**11. Il protocollo dei backtest di base.**
@@ -59,10 +72,14 @@ La Fase 5 porta le tre strategie di base, i correttivi comuni, il motore del ris
- Il costo di andata e ritorno è 2 × (commissione taker + scostamento); lo scostamento è pesato sul controvalore scambiato.
- Il percorso atteso a un anno viene da un bootstrap a blocchi stazionario: 2.000 percorsi, blocchi medi di 20 giorni, seme 20260101, 365 giorni.
- Il rapporto mostra lo Sharpe annuo (× √sedute dell'anno) e DSR e PBO con tre decimali, perché "0,90 serve ≥ 0,90" con due decimali confondeva.
- Il rapporto conta quante volte, per strumento e giorno, un correttivo o una regola di rischio ha cambiato la richiesta della strategia, separate dalle note del motore (ordini sotto il minimo, residui).
- "Comprare e tenere" dell'universo largo compra fin dall'inizio tutte le 47 monete che sono state tra le prime dieci in qualche momento: è un paniere scelto col senno di poi, quindi favorisce il confronto e rende il giudizio sulla strategia più severo, non più indulgente.
**12. L'esito dei backtest viaggia con il codice.** I file `docs/backtests/*.outcome.json` sono inclusi nell'applicazione e letti a ogni avvio. Gli esiti azionari sono "non superato, in attesa delle chiavi Alpaca": senza storico azionario le due strategie azionarie restano in osservazione.
**13. L'esito di `crypto_trend` è "non superato".** Con l'universo largo il calo massimo è del 29,1% (limite 25%); con BTC, ETH e SOL la probabilità di sovra-adattamento è 0,84 (limite 0,40). Rendimento annuo 11,2% contro il 32,9% di comprare e tenere. La strategia resta in osservazione. Non ho cambiato regole o soglie dopo aver visto il risultato: farlo renderebbe il test inutile.
**13. L'esito di `crypto_trend` è "non superato".** Con l'universo largo il calo massimo è del 32,8% (limite 25%); con BTC, ETH e SOL la probabilità di sovra-adattamento è 0,84 (limite 0,40). Rendimento annuo 10,4% contro il 32,9% di comprare e tenere. La strategia resta in osservazione. Non ho cambiato regole o soglie dopo aver visto il risultato: farlo renderebbe il test inutile.
Una prima versione del calcolo usava il cambio dello stesso giorno della barra e dava un calo del 29,1%. Spostare il cambio di un giorno (punto 10) ha mosso il calo di quasi quattro punti: anche questo dice che il risultato è fragile.
**14. La demo è coerente con i mockup.** La modalità dimostrativa semina le decisioni dietro le sue operazioni, 58 giorni di simulazione, una qualifica d'esempio e gli indici delle curve, così Operazioni, Strategie e Rischio mostrano le cifre dei mockup 03, 04 e 07. Nella demo nessuno stadio cambia e i moduli del rischio non ci sono.
+119 -89
View File
@@ -1,6 +1,6 @@
# Backtest di `crypto_trend` (Trend crypto)
**Esito: non superato.** Protocollo non superato. Universo ampio: calo massimo 29,1%, serve ≤ 25%. BTC, ETH e SOL: probabilità di sovra-adattamento (pbo) 0,839, serve ≤ 0,40. Resta in osservazione.
**Esito: non superato.** Protocollo non superato. Universo ampio: calo massimo 32,8%, serve ≤ 25%. BTC, ETH e SOL: probabilità di sovra-adattamento (pbo) 0,835, serve ≤ 0,40. Resta in osservazione.
Calcolato il 2026-11-11 con la versione 1 della strategia. Soglie, griglia dei parametri, costi e date erano fissati prima del calcolo (SPEC 12.2) e non sono stati cambiati dopo.
@@ -18,94 +18,110 @@ Per rifarlo: `anubis backtest base --to 2026-10-31`. Il file dell'esito, letto d
| Prova | Variante scelta | Rendimento annuo | Calo massimo | Netto a costi doppi | DSR | PBO | Esito |
|---|---|---:|---:|---:|---:|---:|---|
| Universo ampio | `coin_vol=10;max_stop=20` | 11,2% | −29,1% | 8.053,52 € | 0,960 | 0,143 | non superata |
| BTC, ETH e SOL | `coin_vol=20;max_stop=15` | 13,8% | −17,3% | 12.845,05 € | 0,971 | 0,839 | non superata |
| Universo ampio | `coin_vol=10;max_stop=20` | 10,4% | −32,8% | 7.264,22 € | 0,924 | 0,085 | non superata |
| BTC, ETH e SOL | `coin_vol=20;max_stop=10` | 12,2% | −15,0% | 10.274,96 € | 0,961 | 0,835 | non superata |
## Cosa conserva il bot
- Calo massimo del backtest: −29,1%. Dal vivo, un calo oltre 1,5 volte questo riporta la strategia indietro (SPEC 12.3).
- Scostamento di prezzo previsto: 11,91 punti base; costo stimato di andata e ritorno 0,64%.
- Percorso atteso al 5° percentile (ricampionamento a blocchi dei rendimenti giornalieri): −4,9% dopo 30 giorni, −7,6% dopo 90, −13,2% dopo 365. Venti sedute di fila sotto questo percorso riportano la strategia indietro.
- Calo massimo del backtest: −32,8%. Dal vivo, un calo oltre 1,5 volte questo riporta la strategia indietro (SPEC 12.3).
- Scostamento di prezzo previsto: 11,94 punti base; costo stimato di andata e ritorno 0,64%.
- Percorso atteso al 5° percentile (ricampionamento a blocchi dei rendimenti giornalieri): −5,1% dopo 30 giorni, −8,0% dopo 90, −14,1% dopo 365. Venti sedute di fila sotto questo percorso riportano la strategia indietro.
## Universo ampio
Le 10 monete con più scambi, scelte ogni mese tra 47 coppie (anche quelle poi chiuse).
Dal 01/01/2019 al 31/10/2026, 2861 chiusure giornaliere, capitale iniziale 10.000,00 €. Variante scelta: `coin_vol=10;max_stop=20` (la zona della griglia dove il risultato cambia meno, non la migliore). Impronta del piano `737ca3a07b9c`, dei dati `8486b858321b`.
Dal 01/01/2019 al 31/10/2026, 2861 chiusure giornaliere, capitale iniziale 10.000,00 €. Variante scelta: `coin_vol=10;max_stop=20` (la zona della griglia dove il risultato cambia meno, non la migliore). Impronta del piano `b5f566d59bfa`, dei dati `840015607150`.
| | Strategia | Comprare e tenere |
|---|---:|---:|
| Risultato netto | 12.984,56 € | 82.750,41 € |
| Rendimento totale | 129,8% | 827,5% |
| Rendimento annuo | 11,2% | 32,9% |
| Volatilità annua | 14,0% | 74,2% |
| Calo massimo | −29,1% (11/2021 → 10/2023) | −85,8% |
| Sharpe annuo | 0,83 | 0,76 |
| Operazioni chiuse | 1826 | 0 |
| Operazioni in guadagno | 14,1% | — |
| Rapporto guadagni/perdite | 1,51 | — |
| Commissioni pagate | 2.975,10 € | 20,00 € |
| Risultato netto | 11.628,28 € | 82.820,55 € |
| Rendimento totale | 116,3% | 828,2% |
| Rendimento annuo | 10,4% | 32,9% |
| Volatilità annua | 14,2% | 74,7% |
| Calo massimo | −32,8% (11/2021 → 10/2023) | −85,8% |
| Sharpe annuo | 0,77 | 0,76 |
| Operazioni chiuse | 1842 | 0 |
| Operazioni in guadagno | 13,1% | — |
| Rapporto guadagni/perdite | 1,47 | — |
| Commissioni pagate | 2.967,95 € | 20,00 € |
| Tempo investito | 16,9% | 92,0% |
**Per anno**
| Anno | Strategia | Comprare e tenere |
|---|---:|---:|
| 2019 | 17,8% | 4,4% |
| 2020 | 34,9% | 103,9% |
| 2021 | 24,9% | 1.603,5% |
| 2022 | −10,5% | −79,9% |
| 2023 | 14,6% | 56,4% |
| 2024 | 26,8% | 34,5% |
| 2025 | −8,8% | −33,1% |
| 2026 | −2,4% | −9,4% |
| 2019 | 17,0% | 4,8% |
| 2020 | 36,2% | 103,2% |
| 2021 | 19,8% | 1.603,8% |
| 2022 | −11,2% | −79,9% |
| 2023 | 12,2% | 56,4% |
| 2024 | 26,2% | 33,8% |
| 2025 | −7,4% | −32,9% |
| 2026 | −2,6% | −9,4% |
**Sensibilità ai costi** (commissioni e scostamento moltiplicati insieme)
| Costi | Risultato netto | Rendimento totale | Sharpe annuo | Calo massimo | Commissioni |
|---|---:|---:|---:|---:|---:|
| ×1 | 12.984,56 € | 129,8% | 0,83 | −29,1% | 2.975,10 € |
| ×2 | 8.053,52 € | 80,5% | 0,61 | −33,9% | 5.005,99 € |
| ×3 | 4.349,38 € | 43,5% | 0,40 | −36,0% | 6.495,29 € |
| ×1 | 11.628,28 € | 116,3% | 0,77 | −32,8% | 2.967,95 € |
| ×2 | 7.264,22 € | 72,6% | 0,56 | −35,8% | 5.039,47 € |
| ×3 | 3.522,91 € | 35,2% | 0,34 | −38,9% | 6.471,34 € |
**Convalide**
- Finestre che avanzano (4, con 29 giorni di stacco): rendimento fuori campione 67,6%, Sharpe annuo 0,65.
- K-fold purgato combinatorio (6 gruppi, 2 di prova, 15 divisioni): Sharpe annuo medio dei percorsi 0,83, peggiore 0,83, percorsi positivi 100,0%.
- Deflated Sharpe Ratio 0,96, contando 9 varianti provate in tutto.
- Probabilità di sovra-adattamento (PBO) 0,14, su 12870 combinazioni di 9 varianti.
- Finestre che avanzano (4, con 29 giorni di stacco): rendimento fuori campione 58,4%, Sharpe annuo 0,58.
- K-fold purgato combinatorio (6 gruppi, 2 di prova, 15 divisioni): Sharpe annuo medio dei percorsi 0,77, peggiore 0,77, percorsi positivi 100,0%.
- Deflated Sharpe Ratio 0,92, contando 9 varianti provate in tutto.
- Probabilità di sovra-adattamento (PBO) 0,09, su 12870 combinazioni di 9 varianti.
- Sguardo in avanti: 8583 decisioni rifatte tagliando i dati in 6 punti, 0 cambiate.
**Soglie**
| Controllo | Valore | Soglia | Esito |
|---|---:|---:|---|
| Risultato netto con costi doppi | 8.053,52 € | > 0,00 € | superato |
| Deflated Sharpe Ratio | 0,960 | ≥ 0,9 | superato |
| Probabilità di sovra-adattamento (PBO) | 0,143 | ≤ 0,4 | superato |
| Calo massimo | 29,1% | ≤ 25% | **non superato** |
| Risultato netto con costi doppi | 7.264,22 € | > 0,00 € | superato |
| Deflated Sharpe Ratio | 0,924 | ≥ 0,9 | superato |
| Probabilità di sovra-adattamento (PBO) | 0,085 | ≤ 0,4 | superato |
| Calo massimo | 32,8% | ≤ 25% | **non superato** |
| Decisioni cambiate aggiungendo dati successivi | 0 | = 0 | superato |
**Varianti della griglia**
| Parametri | Sharpe annuo | Stabilità della zona | Risultato netto | Calo massimo | Operazioni |
|---|---:|---:|---:|---:|---:|
| `coin_vol=10;max_stop=10` | 0,58 | 0,58 | 6.383,12 € | −22,9% | 2243 |
| `coin_vol=10;max_stop=15` | 0,83 | 0,71 | 12.327,24 € | −24,6% | 1994 |
| `coin_vol=10;max_stop=20` (scelta) | 0,83 | 0,78 | 12.984,56 € | −29,1% | 1826 |
| `coin_vol=15;max_stop=10` | 0,53 | 0,53 | 6.035,84 € | −25,0% | 2257 |
| `coin_vol=15;max_stop=15` | 0,74 | 0,67 | 10.656,85 € | −29,4% | 2002 |
| `coin_vol=15;max_stop=20` | 0,74 | 0,74 | 11.167,92 € | −30,8% | 1837 |
| `coin_vol=20;max_stop=10` | 0,44 | 0,44 | 4.826,58 € | −25,0% | 2258 |
| `coin_vol=20;max_stop=15` | 0,65 | 0,63 | 8.943,30 € | −30,5% | 2008 |
| `coin_vol=20;max_stop=20` | 0,66 | 0,66 | 9.921,78 € | −31,1% | 1838 |
| `coin_vol=10;max_stop=10` | 0,54 | 0,54 | 5.784,07 € | −24,0% | 2269 |
| `coin_vol=10;max_stop=15` | 0,86 | 0,66 | 13.191,01 € | −27,8% | 2008 |
| `coin_vol=10;max_stop=20` (scelta) | 0,77 | 0,75 | 11.628,28 € | −32,8% | 1842 |
| `coin_vol=15;max_stop=10` | 0,39 | 0,39 | 3.932,83 € | −26,3% | 2281 |
| `coin_vol=15;max_stop=15` | 0,71 | 0,61 | 10.147,48 € | −31,9% | 2015 |
| `coin_vol=15;max_stop=20` | 0,68 | 0,68 | 9.971,55 € | −33,4% | 1853 |
| `coin_vol=20;max_stop=10` | 0,35 | 0,35 | 3.437,00 € | −26,8% | 2284 |
| `coin_vol=20;max_stop=15` | 0,59 | 0,55 | 7.855,25 € | −33,4% | 2021 |
| `coin_vol=20;max_stop=20` | 0,57 | 0,57 | 7.673,22 € | −34,6% | 1856 |
**Interventi di correttivi e rischio sulla variante scelta**
Quante volte, per strumento e giorno, un correttivo o una regola di rischio ha cambiato ciò che la strategia chiedeva.
| Motivo | Volte |
|---|---:|
| `residue_written_off` | 1823 |
| `below_min_notional` | 387 |
| `crypto_regime_below_average` | 3565 |
| `risk_reduction` | 1590 |
| `crypto_regime_high_volatility` | 151 |
| `trade_risk_limit` | 43 |
| `switch_tripped` | 34 |
| `daily_loss_block` | 14 |
| `stop_above_price` | 13 |
**Note del motore di prova**
Ordini non eseguiti come chiesto: sotto il minimo, residui lasciati dopo un'uscita, liquidità.
| Motivo | Volte |
|---|---:|
| `residue_written_off` | 1837 |
| `below_min_notional` | 449 |
**Strumenti**
@@ -163,81 +179,95 @@ Dal 01/01/2019 al 31/10/2026, 2861 chiusure giornaliere, capitale iniziale 10.00
Solo le tre coppie in euro con la liquidità migliore.
Dal 01/01/2019 al 31/10/2026, 2861 chiusure giornaliere, capitale iniziale 10.000,00 €. Variante scelta: `coin_vol=20;max_stop=15` (la zona della griglia dove il risultato cambia meno, non la migliore). Impronta del piano `3ba7de18ca85`, dei dati `f8e752dabf31`.
Dal 01/01/2019 al 31/10/2026, 2861 chiusure giornaliere, capitale iniziale 10.000,00 €. Variante scelta: `coin_vol=20;max_stop=10` (la zona della griglia dove il risultato cambia meno, non la migliore). Impronta del piano `1ce210e9cbcb`, dei dati `3b890d6f2ef3`.
| | Strategia | Comprare e tenere |
|---|---:|---:|
| Risultato netto | 17.515,31 € | 215.787,99 € |
| Rendimento totale | 175,2% | 2.157,9% |
| Rendimento annuo | 13,8% | 48,9% |
| Volatilità annua | 12,8% | 71,7% |
| Calo massimo | −17,3% (11/2021 → 10/2023) | −86,7% |
| Sharpe annuo | 1,07 | 0,92 |
| Operazioni chiuse | 452 | 0 |
| Operazioni in guadagno | 15,7% | — |
| Rapporto guadagni/perdite | 2,29 | — |
| Commissioni pagate | 2.282,94 € | 20,00 € |
| Tempo investito | 14,9% | 95,2% |
| Risultato netto | 14.642,97 € | 216.831,80 € |
| Rendimento totale | 146,4% | 2.168,3% |
| Rendimento annuo | 12,2% | 49,0% |
| Volatilità annua | 11,8% | 72,2% |
| Calo massimo | −15,0% (11/2021 → 10/2023) | −86,7% |
| Sharpe annuo | 1,03 | 0,92 |
| Operazioni chiuse | 539 | 0 |
| Operazioni in guadagno | 16,7% | — |
| Rapporto guadagni/perdite | 1,76 | — |
| Commissioni pagate | 2.866,85 € | 20,00 € |
| Tempo investito | 12,9% | 95,2% |
**Per anno**
| Anno | Strategia | Comprare e tenere |
|---|---:|---:|
| 2019 | 15,0% | 28,6% |
| 2020 | 30,5% | 221,5% |
| 2021 | 20,9% | 643,3% |
| 2022 | −7,4% | −81,4% |
| 2023 | 29,4% | 256,5% |
| 2024 | 22,8% | 93,3% |
| 2025 | −0,3% | −31,6% |
| 2026 | 3,5% | −16,1% |
| 2019 | 20,8% | 29,3% |
| 2020 | 29,0% | 219,6% |
| 2021 | 14,1% | 647,5% |
| 2022 | −6,7% | −81,5% |
| 2023 | 27,3% | 257,8% |
| 2024 | 20,9% | 92,3% |
| 2025 | −5,5% | −31,3% |
| 2026 | 2,3% | −16,1% |
**Sensibilità ai costi** (commissioni e scostamento moltiplicati insieme)
| Costi | Risultato netto | Rendimento totale | Sharpe annuo | Calo massimo | Commissioni |
|---|---:|---:|---:|---:|---:|
| ×1 | 17.515,31 € | 175,2% | 1,07 | −17,3% | 2.282,94 € |
| ×2 | 12.845,05 € | 128,5% | 0,89 | −20,9% | 4.070,32 € |
| ×3 | 9.959,70 € | 99,6% | 0,75 | −22,7% | 5.605,48 € |
| ×1 | 14.642,97 € | 146,4% | 1,03 | −15,0% | 2.866,85 € |
| ×2 | 10.274,96 € | 102,7% | 0,82 | −18,9% | 5.161,91 € |
| ×3 | 6.273,26 € | 62,7% | 0,59 | −21,3% | 6.782,83 € |
**Convalide**
- Finestre che avanzano (4, con 29 giorni di stacco): rendimento fuori campione 90,3%, Sharpe annuo 0,91.
- K-fold purgato combinatorio (6 gruppi, 2 di prova, 15 divisioni): Sharpe annuo medio dei percorsi 1,00, peggiore 0,94, percorsi positivi 100,0%.
- Deflated Sharpe Ratio 0,97, contando 18 varianti provate in tutto.
- Probabilità di sovra-adattamento (PBO) 0,84, su 12870 combinazioni di 9 varianti.
- Finestre che avanzano (4, con 29 giorni di stacco): rendimento fuori campione 82,4%, Sharpe annuo 0,85.
- K-fold purgato combinatorio (6 gruppi, 2 di prova, 15 divisioni): Sharpe annuo medio dei percorsi 0,90, peggiore 0,82, percorsi positivi 100,0%.
- Deflated Sharpe Ratio 0,96, contando 18 varianti provate in tutto.
- Probabilità di sovra-adattamento (PBO) 0,83, su 12870 combinazioni di 9 varianti.
- Sguardo in avanti: 8583 decisioni rifatte tagliando i dati in 6 punti, 0 cambiate.
**Soglie**
| Controllo | Valore | Soglia | Esito |
|---|---:|---:|---|
| Risultato netto con costi doppi | 12.845,05 € | > 0,00 € | superato |
| Deflated Sharpe Ratio | 0,971 | ≥ 0,9 | superato |
| Probabilità di sovra-adattamento (PBO) | 0,839 | ≤ 0,4 | **non superato** |
| Calo massimo | 17,3% | ≤ 25% | superato |
| Risultato netto con costi doppi | 10.274,96 € | > 0,00 € | superato |
| Deflated Sharpe Ratio | 0,961 | ≥ 0,9 | superato |
| Probabilità di sovra-adattamento (PBO) | 0,835 | ≤ 0,4 | **non superato** |
| Calo massimo | 15,0% | ≤ 25% | superato |
| Decisioni cambiate aggiungendo dati successivi | 0 | = 0 | superato |
**Varianti della griglia**
| Parametri | Sharpe annuo | Stabilità della zona | Risultato netto | Calo massimo | Operazioni |
|---|---:|---:|---:|---:|---:|
| `coin_vol=10;max_stop=10` | 1,01 | 1,00 | 9.436,53 € | −10,9% | 532 |
| `coin_vol=10;max_stop=15` | 0,94 | 0,94 | 9.790,38 € | −13,0% | 452 |
| `coin_vol=10;max_stop=20` | 1,05 | 1,01 | 12.078,19 € | −13,0% | 388 |
| `coin_vol=15;max_stop=10` | 1,04 | 1,03 | 13.029,82 € | −13,3% | 532 |
| `coin_vol=15;max_stop=15` | 1,01 | 1,01 | 14.386,02 € | −15,8% | 452 |
| `coin_vol=15;max_stop=20` | 1,05 | 1,03 | 15.995,77 € | −15,0% | 388 |
| `coin_vol=20;max_stop=10` | 1,09 | 1,05 | 15.920,52 € | −13,9% | 532 |
| `coin_vol=20;max_stop=15` (scelta) | 1,07 | 1,06 | 17.515,31 € | −17,3% | 452 |
| `coin_vol=20;max_stop=20` | 1,08 | 1,05 | 18.543,32 € | −15,5% | 388 |
| `coin_vol=10;max_stop=10` | 0,98 | 0,95 | 8.962,80 € | −11,2% | 539 |
| `coin_vol=10;max_stop=15` | 0,91 | 0,91 | 9.287,93 € | −13,3% | 457 |
| `coin_vol=10;max_stop=20` | 0,97 | 0,95 | 10.893,96 € | −13,9% | 393 |
| `coin_vol=15;max_stop=10` | 1,00 | 0,97 | 12.333,91 € | −13,5% | 539 |
| `coin_vol=15;max_stop=15` | 0,91 | 0,91 | 12.048,69 € | −16,1% | 457 |
| `coin_vol=15;max_stop=20` | 0,99 | 0,96 | 14.421,53 € | −16,5% | 393 |
| `coin_vol=20;max_stop=10` (scelta) | 1,03 | 0,98 | 14.642,97 € | −15,0% | 539 |
| `coin_vol=20;max_stop=15` | 0,97 | 0,97 | 14.521,59 € | −17,1% | 457 |
| `coin_vol=20;max_stop=20` | 1,02 | 0,97 | 16.651,30 € | −16,6% | 393 |
**Interventi di correttivi e rischio sulla variante scelta**
Quante volte, per strumento e giorno, un correttivo o una regola di rischio ha cambiato ciò che la strategia chiedeva.
| Motivo | Volte |
|---|---:|
| `residue_written_off` | 450 |
| `below_min_notional` | 89 |
| `crypto_regime_below_average` | 1104 |
| `crypto_regime_high_volatility` | 52 |
| `trade_risk_limit` | 41 |
| `stop_above_price` | 3 |
| `daily_loss_block` | 1 |
**Note del motore di prova**
Ordini non eseguiti come chiesto: sotto il minimo, residui lasciati dopo un'uscita, liquidità.
| Motivo | Volte |
|---|---:|
| `residue_written_off` | 539 |
| `below_min_notional` | 105 |
**Strumenti**
+337 -336
View File
@@ -1,376 +1,377 @@
{
"passed": false,
"verdict": "Protocollo non superato. Universo ampio: calo massimo 29,1%, serve \u2264 25%. BTC, ETH e SOL: probabilit\u00E0 di sovra-adattamento (pbo) 0,839, serve \u2264 0,40. Resta in osservazione.",
"verdict": "Protocollo non superato. Universo ampio: calo massimo 32,8%, serve \u2264 25%. BTC, ETH e SOL: probabilit\u00E0 di sovra-adattamento (pbo) 0,835, serve \u2264 0,40. Resta in osservazione.",
"report": "docs/backtests/crypto_trend.md",
"plan_hash": "737ca3a07b9c67574013581d6ebc395e60b8edfa0681707804e67601112f1c12",
"max_drawdown": 0.2910,
"expected_slippage_bp": 11.91,
"round_trip_cost": 0.006382,
"plan_hash": "b5f566d59bfae84f7c0821705d243dc0707803db36f74c1eecd130fb14fed8ed",
"parameters": "coin_vol=10;max_stop=20",
"max_drawdown": 0.3278,
"expected_slippage_bp": 11.94,
"round_trip_cost": 0.006388,
"expected_path_p5": [
-0.0099,
-0.0133,
-0.0175,
-0.0205,
-0.0231,
-0.0234,
-0.0242,
-0.026,
-0.0281,
-0.0291,
-0.031,
-0.031,
-0.0334,
-0.034,
-0.0352,
-0.037,
-0.0382,
-0.01,
-0.0144,
-0.0179,
-0.0199,
-0.023,
-0.0252,
-0.0256,
-0.0269,
-0.0284,
-0.0294,
-0.0313,
-0.0316,
-0.0327,
-0.0346,
-0.0355,
-0.0373,
-0.0381,
-0.0396,
-0.0411,
-0.0412,
-0.0405,
-0.0401,
-0.0415,
-0.0421,
-0.0437,
-0.044,
-0.0446,
-0.0458,
-0.0467,
-0.0479,
-0.0489,
-0.0503,
-0.0517,
-0.0528,
-0.0525,
-0.0529,
-0.0539,
-0.0552,
-0.0557,
-0.0563,
-0.0568,
-0.0583,
-0.0413,
-0.0426,
-0.0429,
-0.0445,
-0.0457,
-0.0457,
-0.0468,
-0.0481,
-0.0499,
-0.0512,
-0.0507,
-0.0519,
-0.0538,
-0.0548,
-0.0558,
-0.0566,
-0.0582,
-0.0585,
-0.0595,
-0.0591,
-0.0583,
-0.0587,
-0.0593,
-0.0595,
-0.0596,
-0.0613,
-0.0609,
-0.0618,
-0.0629,
-0.0638,
-0.0641,
-0.0594,
-0.0599,
-0.06,
-0.06,
-0.0616,
-0.0619,
-0.0619,
-0.061,
-0.0626,
-0.0634,
-0.0655,
-0.0646,
-0.0649,
-0.066,
-0.0659,
-0.067,
-0.0676,
-0.0693,
-0.0692,
-0.0697,
-0.0686,
-0.0687,
-0.0693,
-0.0693,
-0.0697,
-0.0696,
-0.069,
-0.069,
-0.0716,
-0.0651,
-0.0674,
-0.0681,
-0.0683,
-0.0678,
-0.0684,
-0.0691,
-0.0705,
-0.0724,
-0.0733,
-0.0725,
-0.0727,
-0.073,
-0.073,
-0.0734,
-0.0735,
-0.0738,
-0.074,
-0.0747,
-0.074,
-0.0757,
-0.0741,
-0.0742,
-0.0736,
-0.0737,
-0.0746,
-0.0729,
-0.074,
-0.0737,
-0.0744,
-0.0739,
-0.0751,
-0.0742,
-0.0749,
-0.076,
-0.0754,
-0.0755,
-0.0757,
-0.0756,
-0.0761,
-0.0757,
-0.0761,
-0.0771,
-0.0774,
-0.0781,
-0.0782,
-0.0776,
-0.0791,
-0.0786,
-0.0785,
-0.0807,
-0.0819,
-0.0827,
-0.0823,
-0.083,
-0.0823,
-0.0831,
-0.0829,
-0.0853,
-0.0849,
-0.0836,
-0.0781,
-0.0785,
-0.0789,
-0.0788,
-0.0806,
-0.0802,
-0.0802,
-0.0802,
-0.0813,
-0.0826,
-0.0842,
-0.0841,
-0.0835,
-0.084,
-0.0857,
-0.0856,
-0.0852,
-0.0861,
-0.0861,
-0.0861,
-0.0848,
-0.0861,
-0.0866,
-0.087,
-0.0859,
-0.0855,
-0.0868,
-0.0868,
-0.0875,
-0.0872,
-0.0872,
-0.0876,
-0.0868,
-0.0866,
-0.0865,
-0.0867,
-0.0875,
-0.0877,
-0.0884,
-0.0882,
-0.0887,
-0.0897,
-0.0906,
-0.0902,
-0.0916,
-0.0917,
-0.0922,
-0.0937,
-0.0922,
-0.0931,
-0.0926,
-0.0922,
-0.0914,
-0.0914,
-0.0901,
-0.0916,
-0.0917,
-0.0937,
-0.0937,
-0.0955,
-0.0971,
-0.0882,
-0.0888,
-0.0895,
-0.0912,
-0.0919,
-0.0915,
-0.0929,
-0.0933,
-0.0938,
-0.0941,
-0.0943,
-0.0957,
-0.096,
-0.0957,
-0.0958,
-0.0957,
-0.0973,
-0.0965,
-0.0957,
-0.0941,
-0.0956,
-0.0958,
-0.0969,
-0.0972,
-0.0992,
-0.1007,
-0.101,
-0.1004,
-0.1008,
-0.0988,
-0.0996,
-0.1003,
-0.1005,
-0.1025,
-0.1024,
-0.1034,
-0.1027,
-0.1034,
-0.1042,
-0.1034,
-0.105,
-0.1037,
-0.1054,
-0.1066,
-0.1053,
-0.1055,
-0.0996,
-0.101,
-0.1006,
-0.1041,
-0.1051,
-0.1045,
-0.1032,
-0.1035,
-0.1038,
-0.1048,
-0.1045,
-0.1067,
-0.1051,
-0.1065,
-0.1061,
-0.1062,
-0.1057,
-0.1057,
-0.1072,
-0.1071,
-0.108,
-0.108,
-0.1087,
-0.1102,
-0.1118,
-0.1117,
-0.111,
-0.1112,
-0.111,
-0.1132,
-0.1082,
-0.1073,
-0.1078,
-0.1088,
-0.109,
-0.1097,
-0.1116,
-0.1089,
-0.1105,
-0.1103,
-0.1083,
-0.1116,
-0.1108,
-0.1112,
-0.1119,
-0.1113,
-0.1127,
-0.1129,
-0.1129,
-0.1127,
-0.1143,
-0.1139,
-0.1162,
-0.1156,
-0.1159,
-0.1154,
-0.1173,
-0.116,
-0.1147,
-0.1162,
-0.1139,
-0.1135,
-0.1135,
-0.1138,
-0.1116,
-0.1132,
-0.1133,
-0.1144,
-0.1136,
-0.1136,
-0.1139,
-0.1131,
-0.1132,
-0.114,
-0.1151,
-0.1147,
-0.1148,
-0.1163,
-0.1161,
-0.1169,
-0.1164,
-0.1179,
-0.1179,
-0.1201,
-0.1141,
-0.1144,
-0.1159,
-0.116,
-0.1165,
-0.1157,
-0.1165,
-0.1191,
-0.1195,
-0.1198,
-0.1205,
-0.12,
-0.1216,
-0.1213,
-0.1219,
-0.1204,
-0.12,
-0.1217,
-0.1194,
-0.1206,
-0.1211,
-0.122,
-0.1227,
-0.1218,
-0.1221,
-0.1222,
-0.1222,
-0.1233,
-0.123,
-0.123,
-0.1229,
-0.1231,
-0.1225,
-0.1212,
-0.1194,
-0.1184,
-0.1195,
-0.119,
-0.1195,
-0.1201,
-0.1202,
-0.1203,
-0.121,
-0.1228,
-0.1225,
-0.1221,
-0.1222,
-0.1222,
-0.1223,
-0.1223,
-0.1223,
-0.1241,
-0.1238,
-0.126,
-0.1252,
-0.1269,
-0.1266,
-0.1265,
-0.1258,
-0.1245,
-0.1261,
-0.1206,
-0.1195,
-0.1217,
-0.1212,
-0.1204,
-0.1217,
-0.1229,
-0.124,
-0.1231,
-0.1232,
-0.1247,
-0.1256,
-0.1258,
-0.1261,
-0.1263,
-0.1254,
-0.1272,
-0.1266,
-0.1266,
-0.1268,
-0.1273,
-0.1287,
-0.1275,
-0.1288,
-0.1269,
-0.1268,
-0.1273,
-0.1272,
-0.1269,
-0.1262,
-0.1259,
-0.1273,
-0.1267,
-0.1268,
-0.1259,
-0.1266,
-0.1257,
-0.1267,
-0.1272,
-0.1267,
-0.1268,
-0.126,
-0.1269,
-0.1267,
-0.1256,
-0.1256,
-0.1254,
-0.1258,
-0.1267,
-0.127,
-0.1275,
-0.1291,
-0.1262,
-0.1273,
-0.1287,
-0.129,
-0.1292,
-0.1278,
-0.125,
-0.1259,
-0.1273,
-0.1278,
-0.1278,
-0.1274,
-0.1253,
-0.1257,
-0.1237,
-0.1237,
-0.1244,
-0.1236,
-0.1242,
-0.1242,
-0.1248,
-0.1258,
-0.1266,
-0.127,
-0.126,
-0.126,
-0.1264,
-0.1263,
-0.1263,
-0.1268,
-0.1263,
-0.1249,
-0.1281,
-0.1282,
-0.1265,
-0.126,
-0.1262,
-0.1259,
-0.1281,
-0.1275,
-0.1296,
-0.1299,
-0.1277,
-0.1286,
-0.1299,
-0.1292,
-0.128,
-0.1304,
-0.1309,
-0.1271,
-0.1276,
-0.1301,
-0.1289,
-0.1273,
-0.1289,
-0.1285,
-0.1272,
-0.1265,
-0.1257,
-0.1273,
-0.127,
-0.1244,
-0.1244,
-0.125,
-0.126,
-0.1261,
-0.1262,
-0.1249,
-0.1243,
-0.1255,
-0.1267,
-0.1269,
-0.1283,
-0.1288,
-0.1296,
-0.1314,
-0.1302,
-0.1313,
-0.1319,
-0.1308,
-0.1308,
-0.1307,
-0.1297,
-0.1303,
-0.1298,
-0.1322,
-0.1323,
-0.1323,
-0.1316,
-0.1311,
-0.1325,
-0.1322,
-0.1315,
-0.1337,
-0.1319,
-0.1309,
-0.1341,
-0.1328,
-0.1323,
-0.1346,
-0.1315,
-0.1328,
-0.1353,
-0.1347,
-0.1338,
-0.1365,
-0.1356,
-0.1338,
-0.1346,
-0.1343,
-0.134,
-0.1345,
-0.1331,
-0.1332,
-0.1347,
-0.1339,
-0.136,
-0.1347,
-0.1348,
-0.1368,
-0.136,
-0.1356,
-0.1313,
-0.1334,
-0.134,
-0.1349,
-0.1341,
-0.1342,
-0.1341,
-0.135,
-0.1353,
-0.1319,
-0.1345,
-0.137,
-0.1358,
-0.1369,
-0.1368,
-0.1372,
-0.1347,
-0.1376,
-0.1345,
-0.1346,
-0.1343,
-0.1344,
-0.132,
-0.1331,
-0.133,
-0.1345,
-0.1347,
-0.1355,
-0.1349,
-0.1346,
-0.1341,
-0.1339,
-0.1336,
-0.1332,
-0.1318,
-0.132
-0.1334,
-0.1326,
-0.1343,
-0.134,
-0.1342,
-0.1351,
-0.135,
-0.1352,
-0.1353,
-0.1382,
-0.1366,
-0.1363,
-0.1368,
-0.1354,
-0.1352,
-0.1383,
-0.1382,
-0.1356,
-0.1354,
-0.1349,
-0.1379,
-0.1382,
-0.1364,
-0.1364,
-0.1348,
-0.1345,
-0.1346,
-0.1353,
-0.1342,
-0.1372,
-0.1386,
-0.1385,
-0.1388,
-0.1402,
-0.1399,
-0.1397,
-0.1397,
-0.1401,
-0.1393,
-0.1394,
-0.1417,
-0.1402,
-0.1399,
-0.1409,
-0.1417,
-0.1404,
-0.1408,
-0.1418,
-0.1422,
-0.1423,
-0.1444,
-0.1423,
-0.1399,
-0.1405
]
}
+1 -1
View File
@@ -6,5 +6,5 @@ Per provare le strategie sulle azioni servono gli storici giornalieri di Alpaca,
Finché manca il backtest la strategia resta in osservazione: guarda il mercato e scrive le sue decisioni nel diario, ma non opera, nemmeno in simulazione.
Quando avrai inserito le chiavi nelle Impostazioni, il bot raccoglie gli storici. Poi dal Laboratorio lanci la prova della strategia con l'origine "barre raccolte": se supera le soglie di SPEC 12.2, la porti in simulazione dalla pagina Strategie.
Quando avrai inserito le chiavi nelle Impostazioni, il bot raccoglie gli storici. Poi il backtest si rifà con gli stessi controlli di crypto_trend e il nuovo esito arriva con un aggiornamento del programma: se supera le soglie, la strategia parte in simulazione da sola al primo avvio dopo l'aggiornamento.
+1 -1
View File
@@ -6,5 +6,5 @@ Per provare le strategie sulle azioni servono gli storici giornalieri di Alpaca,
Finché manca il backtest la strategia resta in osservazione: guarda il mercato e scrive le sue decisioni nel diario, ma non opera, nemmeno in simulazione.
Quando avrai inserito le chiavi nelle Impostazioni, il bot raccoglie gli storici. Poi dal Laboratorio lanci la prova della strategia con l'origine "barre raccolte": se supera le soglie di SPEC 12.2, la porti in simulazione dalla pagina Strategie.
Quando avrai inserito le chiavi nelle Impostazioni, il bot raccoglie gli storici. Poi il backtest si rifà con gli stessi controlli di crypto_trend e il nuovo esito arriva con un aggiornamento del programma: se supera le soglie, la strategia parte in simulazione da sola al primo avvio dopo l'aggiornamento.
+1
View File
@@ -472,6 +472,7 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
.confirm-live summary { list-style: none; align-self: flex-start; display: inline-flex; }
.confirm-live summary::-webkit-details-marker { display: none; }
.confirm-live[open] summary { margin-bottom: 12px; }
.confirm-summary { margin: 0; padding-left: 20px; display: grid; gap: 4px; }
.form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px 16px; align-items: end; }
.form-grid > p { grid-column: 1 / -1; }
.form-grid label { display: flex; flex-direction: column; gap: 6px; font-weight: 550; }
@@ -443,7 +443,8 @@
"limite" => "Un limite non è valido: controlla che ogni valore sia un numero dentro il suo intervallo.",
"ordine-limiti" => "Il dimezzamento sul calo dal massimo deve venire prima dell'interruttore, e la perdita di un giorno non può superare quella di una settimana.",
"frase-rischio" => $"Una strategia usa soldi veri: per aggiungere rischio scrivi la frase «{StageBook.RaisePhrase}». Non ho cambiato nulla.",
"password-rischio" => "Password o codice non corretti. Non ho cambiato nulla.",
"password-rischio" => "Password o codice non corretti. Dopo cinque tentativi sbagliati devi aspettare 15 minuti. Non ho cambiato nulla.",
"retrocessione-rischio" => "Una strategia con soldi veri ha una condizione di retrocessione in corso: finché dura non si aggiunge rischio. Non ho cambiato nulla.",
"scenari" => "Gli scenari non sono validi: una riga ciascuno, con descrizione e tre percentuali separate da punto e virgola.",
_ => PasswordMessages.For(Errore),
@@ -254,7 +254,7 @@
</ul>
@if (r.Notes.Count > 0)
{
<h3>Ordini non eseguiti come chiesto</h3>
<h3>Decisioni e ordini non eseguiti come chiesto</h3>
<ul>
@foreach (var (reason, count) in r.Notes.OrderByDescending(n => n.Value))
{
@@ -22,14 +22,21 @@
<h2 id="interruttore">Interruttore d'emergenza</h2>
<span class="link-state @(v.BotState == "active" ? null : "down")"><span class="dot"></span>@BotText(v.BotState)</span>
</div>
@if (v.BotState == "stopped")
@if (v.WaitsForRestart)
{
<p class="notice notice-attention" role="status"><Icon Name="alert" Size="16" /><span>
@if (v.Risk.State.Tripped)
@if (v.Tripped.Count > 0)
{
<text>L'interruttore è scattato: il calo dal massimo ha superato il @Format.Percent(v.Limits.DrawdownStop * 100m, 0). </text>
<text>L'interruttore è scattato @string.Join(" e ", v.Tripped.Select(t => Where(t.World))): il calo dal massimo ha superato il @Format.Percent(v.Limits.DrawdownStop * 100m, 0). </text>
}
@if (v.BotState == "stopped")
{
<text>Il bot non apre posizioni e non vende per le strategie; gli stop di protezione restano attivi.</text>
}
else
{
<text>Lì non apro posizioni e non vendo per le strategie; gli stop di protezione restano attivi. Il resto continua a lavorare.</text>
}
Il bot non apre posizioni e non vende per le strategie; gli stop di protezione restano attivi.
@if (v.CloseAllPending)
{
<text> Sta vendendo tutte le posizioni: ciò che è su un mercato chiuso parte all'apertura.</text>
@@ -48,7 +55,7 @@
</form>
}
}
else
@if (v.BotState != "stopped")
{
<p>Con <strong>Ferma tutto</strong> annullo gli ordini in attesa e non apro nuove posizioni. Gli stop di protezione restano attivi, così quello che è aperto non rimane scoperto. Per ripartire serve la tua conferma, da qui.</p>
@if (!Shell.IsDemo)
@@ -70,9 +77,9 @@
else
{
<ul class="blocks">
@if (v.Risk.State.Tripped)
@foreach (var t in v.Tripped)
{
<li class="loss"><Icon Name="alert" Size="16" />Interruttore scattato @(v.Risk.State.TrippedAt is { } at ? "il " + Moment(at) : ""): aspetta la tua conferma.</li>
<li class="loss"><Icon Name="alert" Size="16" />Interruttore scattato @Where(t.World) @(t.State.TrippedAt is { } at ? "il " + Moment(at) : ""): aspetta la tua conferma.</li>
}
@if (v.Risk.State.DailyBlockUntil is { } until && until > Clock.UtcNow)
{
@@ -90,7 +97,7 @@
{
<li><Icon Name="pause" Size="16" />Bot in pausa: niente nuovi ingressi, stop e uscite proseguono.</li>
}
@if (v.BotState == "stopped" && !v.Risk.State.Tripped)
@if (v.BotState == "stopped" && v.Tripped.Count == 0)
{
<li class="loss"><Icon Name="stop" Size="16" />Ferma tutto acceso.</li>
}
@@ -284,7 +291,9 @@
_ => "Fermo",
};
private static string RestartText(RiskView v) => v.Risk.State.Tripped
private static string Where(string world) => world == Worlds.Real ? "sui conti veri" : "nel mondo simulato";
private static string RestartText(RiskView v) => v.Tripped.Count > 0
? "Riparti: il massimo di riferimento riparte dal patrimonio di adesso e il bot torna a operare. Confermi?"
: "Riparti: il bot torna a operare. Confermi?";
@@ -75,6 +75,10 @@
<dt>Calo peggiore</dt><dd><strong>@Format.Percent(s.WorstFall * 100m, 1)</strong></dd>
<dt>Operazioni chiuse</dt><dd><strong>@s.Closed@(s.Closed > 0 ? $", di cui {s.Winners} in guadagno" : "")</strong></dd>
<dt>Posizioni aperte</dt><dd><strong>@(s.Open.Count == 0 ? "nessuna" : string.Join(", ", s.Open.Distinct()))</strong></dd>
@if (s.TwinGap is { } gap)
{
<dt>Rispetto al gemello simulato</dt><dd><strong>@Format.Percent(gap, 2, withSign: true)</strong> <span class="muted">del capitale usato</span></dd>
}
</dl>
</div>
<div class="strategy-steps">
@@ -122,7 +126,14 @@
<summary class="btn">@target</summary>
<form method="post" action="/azioni/strategie/@s.Stage.Strategy/reale" class="form-grid">
<AntiforgeryToken />
<p>Stai per affidare soldi veri a <strong>@s.Name</strong>@(s.Stage.Stage == StrategyStages.Simulation ? ", con un quarto del capitale" : ""). Per confermare scrivi la frase qui sotto e la tua password.</p>
<p>Stai per affidare soldi veri a <strong>@s.Name</strong>@(s.Stage.Stage == StrategyStages.Simulation ? ", con un quarto del capitale" : ""). Ecco cosa cambia:</p>
<ul class="confirm-summary">
@foreach (var line in s.Summary)
{
<li>@line</li>
}
</ul>
<p>Per confermare scrivi la frase qui sotto e la tua password.</p>
<label>Conto reale
<select name="conto" required>
@foreach (var a in accounts)
@@ -210,8 +221,9 @@
("osservazione", _) => ("Fatto: la strategia è in osservazione.", true),
("reale", _) => ("Fatto: la strategia usa soldi veri da adesso. Se peggiora torna indietro da sola.", true),
(_, "backtest") => ("Solo una strategia che ha superato il backtest può andare in simulazione.", false),
(_, "osservazione-giorni") => ($"Prima della simulazione servono almeno {StageBook.ObservationDays} giorni di segnali raccolti dal vivo in osservazione.", false),
(_, "frase") => ("La frase non corrisponde: scrivila esattamente come è mostrata.", false),
(_, "password") => ("Password o codice non corretti.", false),
(_, "password") => ("Password o codice non corretti. Dopo cinque tentativi sbagliati devi aspettare 15 minuti.", false),
(_, "requisiti") => ("Non tutti i requisiti sono soddisfatti.", false),
(_, "conto") => ("Il conto scelto non è il conto reale del broker di questa strategia.", false),
(_, "consenso") => ("La configurazione d'avvio non consente i soldi veri.", false),
+12
View File
@@ -133,6 +133,13 @@ internal static partial class Endpoints
return Error(StatusCodes.Status400BadRequest, "usa_i_comandi", "Lo stato del bot si cambia con pausa, ripresa e Ferma tutto.");
}
// Risk limits go only through the settings page, which checks their order and asks for the confirmation of
// SPEC 12.4 when a limit goes up while a strategy uses real money: the check holds on the API too.
if (Anubis.Risk.RiskSettings.All.Any(d => d.Key == key))
{
return Error(StatusCodes.Status400BadRequest, "usa_le_impostazioni", "I limiti di rischio si cambiano da Impostazioni, con la conferma quando servono soldi veri.");
}
return await SetSettingAsync(host, key, body.Value, context, ct).ConfigureAwait(false);
});
@@ -252,6 +259,10 @@ internal static partial class Endpoints
{
var settings = host.Services!.Settings;
var current = (await settings.GetAsync(SettingsStore.BotState.Key, ct).ConfigureAwait(false)).Value;
// A switch tripped by the fall from the high stops only its world and leaves the bot "active": the restart is
// the user's confirmation for that world too (SPEC 9.2, 9.3).
var tripped = host.Services.Trading?.Risk is { } engine && await engine.AnyTrippedAsync(ct).ConfigureAwait(false);
var target = command switch
{
"pause" or "pausa" when current == "active" => "paused",
@@ -259,6 +270,7 @@ internal static partial class Endpoints
"stop" or "ferma" => "stopped",
"close" or "chiudi" => "stopped",
"restart" or "riattiva" when current == "stopped" => "active",
"restart" or "riattiva" when tripped => current,
_ => null,
};
if (target is null)
+15 -7
View File
@@ -294,7 +294,7 @@ internal static partial class Forms
}
/// <summary>The capital entrusted to a broker, in euro (SPEC 7.1, 8.6): only the user sets it.</summary>
private static async Task<IResult> SetCapitalAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
private static async Task<IResult> SetCapitalAsync(string broker, IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca))
@@ -314,7 +314,7 @@ internal static partial class Forms
// More capital while a strategy of this broker has real money is more risk: it needs the procedure (SPEC 12.4).
if ((await trading.Capital.EntrustedAsync(broker, ct).ConfigureAwait(false))?.AmountEur is { } before && amount > before &&
await RaiseRefusalAsync(host.Services!, broker, form, ct).ConfigureAwait(false) is { } refusal)
await RaiseRefusalAsync(host.Services!, clock, broker, form, ct).ConfigureAwait(false) is { } refusal)
{
return Results.Redirect(back + "?errore=" + refusal + "#conti");
}
@@ -392,6 +392,8 @@ internal static partial class Forms
"phrase" => "frase",
"password" => "password",
"requirements" => "requisiti",
"backtest" => "backtest",
"observation" => "osservazione-giorni",
"account" => "conto",
Anubis.Risk.RiskReasons.NoConsent => "consenso",
_ => "scelta",
@@ -404,7 +406,7 @@ internal static partial class Forms
/// The risk limits (SPEC 9.2, 13.5), all at once. Lowering is always allowed; raising any of them while a strategy
/// has real money needs the phrase, the password and the second factor (SPEC 12.4).
/// </summary>
private static async Task<IResult> SetLimitsAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
private static async Task<IResult> SetLimitsAsync(IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct)
{
const string back = "/impostazioni";
if (host.IsDemo || host.Services is not { } services)
@@ -440,7 +442,7 @@ internal static partial class Forms
if (Anubis.Risk.RiskSettings.From(k => current[k]).RaisedBy(limits))
{
if (await RaiseRefusalAsync(services, null, form, ct).ConfigureAwait(false) is { } refusal)
if (await RaiseRefusalAsync(services, clock, null, form, ct).ConfigureAwait(false) is { } refusal)
{
return Results.Redirect(back + "?errore=" + refusal + "#rischio");
}
@@ -469,9 +471,10 @@ internal static partial class Forms
}
/// <summary>Null when more risk may go ahead; otherwise the error code for the page.</summary>
private static async Task<string?> RaiseRefusalAsync(AppServices services, string? broker, IFormCollection form, CancellationToken ct)
private static async Task<string?> RaiseRefusalAsync(AppServices services, IClock clock, string? broker, IFormCollection form, CancellationToken ct)
{
var stages = services.Trading?.Stages ?? new Anubis.Trading.StageBook(services.Db, new SystemClock(), Anubis.Trading.TradingConsent.None, (_, _, _) => Task.FromResult(false));
// Without the trading engine no strategy can hold real money, so the stage book only has to say so.
var stages = services.Trading?.Stages ?? new Anubis.Trading.StageBook(services.Db, clock, Anubis.Trading.TradingConsent.None, (_, _, _) => Task.FromResult(false));
try
{
var code = form["codice"].ToString();
@@ -480,7 +483,12 @@ internal static partial class Forms
}
catch (Anubis.Trading.LiveConfirmationException ex)
{
return ex.Code == "phrase" ? "frase-rischio" : "password-rischio";
return ex.Code switch
{
"phrase" => "frase-rischio",
"demotion" => "retrocessione-rischio",
_ => "password-rischio",
};
}
}
+2
View File
@@ -83,6 +83,8 @@ internal static class LabText
BacktestReasons.NoShortSelling => "Vendite allo scoperto rifiutate",
BacktestReasons.WrittenOff => "Residui sotto il minimo lasciati dopo un'uscita",
BacktestReasons.Dividend => "Dividendi incassati",
_ when reason.StartsWith(BacktestReasons.AdjustedPrefix, StringComparison.Ordinal) =>
"Decisioni cambiate da correttivi e rischio (" + ReasonTexts.Text(reason[BacktestReasons.AdjustedPrefix.Length..]).TrimEnd('.') + ")",
_ => "Ordini sotto il minimo dello strumento, non inviati",
};
}
+26 -8
View File
@@ -30,9 +30,13 @@ internal sealed record RiskView(
(DateTimeOffset From, DateTimeOffset To, string Title)? NextCalendarBlock,
(DateTimeOffset From, DateTimeOffset To, string Title)? LastCalendarBlock,
bool PdtGuard,
bool HasPositions)
bool HasPositions,
IReadOnlyList<WorldRisk> Tripped)
{
public bool AnyBlock => Risk.State.Tripped || Risk.EntriesBlocked || Risk.Multiplier < 1m || BotState != "active";
public bool AnyBlock => Tripped.Count > 0 || Risk.EntriesBlocked || Risk.Multiplier < 1m || BotState != "active";
/// <summary>The switch tripped by itself in a world (SPEC 9.2): it waits for the user's restart, like "Ferma tutto".</summary>
public bool WaitsForRestart => BotState == "stopped" || Tripped.Count > 0;
public static async Task<RiskView> LoadAsync(AppServices services, IClock clock, TimeZoneInfo zone, CancellationToken cancellationToken)
{
@@ -44,6 +48,20 @@ internal sealed record RiskView(
var accounts = await AccountsView.LoadAsync(services, clock, zone, cancellationToken).ConfigureAwait(false);
var world = accounts.Accounts.Any(a => TradingEnvironments.World(a.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated;
var risk = await engine.WorldAsync(world, cancellationToken).ConfigureAwait(false);
// Both worlds: a switch tripped in the simulation must show even when the page measures the real one.
var tripped = new List<WorldRisk>();
foreach (var w in new[] { Worlds.Real, Worlds.Simulated })
{
var each = w == world ? risk : await engine.WorldAsync(w, cancellationToken).ConfigureAwait(false);
if (each.State.Tripped)
{
tripped.Add(each);
}
}
// Weights, crypto and the risk of a trade are measured on the reference equity, as the risk engine does (SPEC 9.2).
var reference = await engine.ReferenceAsync(cancellationToken).ConfigureAwait(false);
var bot = (await services.Settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value;
var now = clock.UtcNow;
@@ -80,13 +98,13 @@ internal sealed record RiskView(
$"A {Pct(-limits.DrawdownHalf, 0)} dimezzo il rischio. A {Pct(-limits.DrawdownStop, 0)} fermo tutto e aspetto te", RiskSettings.DrawdownStop.Key),
new("Capitale investito", equity > 0m ? Pct(accounts.InvestedEur / equity, 1) : "—", null, equity > 0m ? Use(accounts.InvestedEur / equity, limits.MaxInvested) : null,
Pct(limits.MaxInvested, 0), "Non compro altro: non uso mai soldi presi in prestito", RiskSettings.MaxInvested.Key),
new("Peso di una sola posizione", biggest is null || equity <= 0m ? "—" : Pct(biggest.ValueEur / equity, 1), biggest?.Symbol,
biggest is null || equity <= 0m ? 0m : Use(biggest.ValueEur / equity, limits.MaxPosition), Pct(limits.MaxPosition, 0), "Riduco la posizione fino alla soglia",
new("Peso di una sola posizione", biggest is null || reference <= 0m ? "—" : Pct(biggest.ValueEur / reference, 1), biggest?.Symbol,
biggest is null || reference <= 0m ? 0m : Use(biggest.ValueEur / reference, limits.MaxPosition), Pct(limits.MaxPosition, 0), "Riduco la posizione fino alla soglia",
RiskSettings.MaxPosition.Key),
new("Crypto sul totale", equity > 0m ? Pct(crypto / equity, 1) : "—", null, equity > 0m ? Use(crypto / equity, limits.MaxCrypto) : null, Pct(limits.MaxCrypto, 0),
new("Crypto sul totale", reference > 0m ? Pct(crypto / reference, 1) : "—", null, reference > 0m ? Use(crypto / reference, limits.MaxCrypto) : null, Pct(limits.MaxCrypto, 0),
"Niente nuovi acquisti di crypto", RiskSettings.MaxCrypto.Key),
new("Rischio di una singola operazione", atRisk.Count == 0 || equity <= 0m ? "—" : Pct(atRisk.Average() / equity), atRisk.Count == 0 ? null : "in media, fino allo stop",
atRisk.Count == 0 || equity <= 0m ? 0m : Use(atRisk.Average() / equity, limits.MaxTradeRisk), Pct(limits.MaxTradeRisk), "Rimpicciolisco l'ordine prima di inviarlo",
new("Rischio di una singola operazione", atRisk.Count == 0 || reference <= 0m ? "—" : Pct(atRisk.Average() / reference), atRisk.Count == 0 ? null : "in media, oggi fino allo stop",
atRisk.Count == 0 || reference <= 0m ? 0m : Use(atRisk.Average() / reference, limits.MaxTradeRisk), Pct(limits.MaxTradeRisk), "All'acquisto rimpicciolisco l'ordine prima di inviarlo",
RiskSettings.MaxTradeRisk.Key),
new("Ordini al minuto", perMinute.ToString(System.Globalization.CultureInfo.InvariantCulture), null, Use(perMinute, limits.OrdersPerMinute),
limits.OrdersPerMinute.ToString(System.Globalization.CultureInfo.InvariantCulture), "Mi fermo e ti avviso: può essere un guasto", RiskSettings.OrdersPerMinute.Key),
@@ -115,7 +133,7 @@ internal sealed record RiskView(
return new RiskView(bot, engine.StopRequested, (await engine.BotAsync(cancellationToken).ConfigureAwait(false)).CloseAll, world, risk, limits, rows, drawdown, scenarios,
await engine.EventsAsync(8, cancellationToken).ConfigureAwait(false), next, last, await RiskSettings.PdtGuardAsync(services.Settings, cancellationToken).ConfigureAwait(false),
positions.Count > 0);
positions.Count > 0, tripped);
}
private static decimal? Worst(IReadOnlyList<IndexPoint> index, DateTimeOffset? from)
+48 -4
View File
@@ -24,7 +24,9 @@ internal sealed record StrategyCard(
IReadOnlyList<(DateTimeOffset At, decimal Index)> Curve,
IReadOnlyList<Requirement> Requirements,
string Phrase,
int? DaysToGo)
int? DaysToGo,
IReadOnlyList<string> Summary,
decimal? TwinGap)
{
public string Color => "var(--s-" + Stage.Strategy.Replace('_', '-') + ")";
@@ -74,6 +76,11 @@ internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, bool Li
.ConfigureAwait(false);
var equities = await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false);
var positions = await ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false);
var limits = await Anubis.Risk.RiskSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false);
decimal? reference = services.Trading?.Risk is { } risk ? await risk.ReferenceAsync(cancellationToken).ConfigureAwait(false) : null;
async Task<string> SymbolAsync(Guid instrument) =>
await services.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT symbol FROM instruments WHERE id = @id", r => r.Text("symbol"), ("id", instrument)), cancellationToken)
.ConfigureAwait(false) ?? "?";
var cards = new List<StrategyCard>();
foreach (var stage in await stages.AllAsync(cancellationToken).ConfigureAwait(false))
{
@@ -112,8 +119,45 @@ internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, bool Li
var symbols = new List<string>();
foreach (var p in positions.Where(p => p.AccountId == ledgerAccount && p.Strategy == stage.Strategy))
{
symbols.Add(await services.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT symbol FROM instruments WHERE id = @id", r => r.Text("symbol"), ("id", p.InstrumentId)),
cancellationToken).ConfigureAwait(false) ?? "?");
symbols.Add(await SymbolAsync(p.InstrumentId).ConfigureAwait(false));
}
// What the confirmation of SPEC 12.4 changes: the capital used, the purchases of the first cycle (estimated
// from what the simulation holds today) and the limits with their base.
var summary = new List<string>();
if (stage.Stage is StrategyStages.Simulation or StrategyStages.Reduced)
{
var toReduced = stage.Stage == StrategyStages.Simulation;
var factor = toReduced ? StrategyStages.ReducedShare : 1m;
var simEquity = equities.FirstOrDefault(e => e.AccountId == stage.AccountId && e.Strategy == stage.Strategy);
var simUsd = accounts.FirstOrDefault(a => a.Id == stage.AccountId).Currency == "USD";
decimal SimEur(decimal amount) => simUsd ? (rate > 0m ? amount / rate : 0m) : amount;
summary.Add(toReduced
? $"Capitale usato: un quarto di quello assegnato, {Format.Money(SimEur(simEquity?.Flows ?? 0m) * factor, decimals: 0)}."
: $"Capitale usato: tutto quello assegnato, {Format.Money(SimEur(simEquity?.Flows ?? 0m), decimals: 0)}.");
var buys = new List<string>();
foreach (var p in positions.Where(p => p.AccountId == stage.AccountId && p.Strategy == stage.Strategy && p.Quantity > 0m))
{
buys.Add($"{await SymbolAsync(p.InstrumentId).ConfigureAwait(false)} per circa {Format.Money(SimEur(p.Value) * factor, decimals: 0)}");
}
summary.Add(buys.Count == 0
? "Acquisti al primo ciclo: nessuno per ora, la simulazione non tiene posizioni."
: (toReduced ? "Acquisti al primo ciclo, stimati da ciò che la simulazione tiene oggi: " : "Al primo ciclo le posizioni vere crescono fino alla misura piena: ") +
string.Join(", ", buys) + ".");
summary.Add("Limiti che valgono: perdita in un giorno " + Format.Percent(limits.DailyLoss * 100m, 1) + ", calo dal massimo " +
Format.Percent(limits.DrawdownHalf * 100m, 0) + " e " + Format.Percent(limits.DrawdownStop * 100m, 0) + ", una posizione " +
Format.Percent(limits.MaxPosition * 100m, 0) + ", rischio di un'operazione " + Format.Percent(limits.MaxTradeRisk * 100m, 1) +
", misurati sul patrimonio di riferimento" + (reference is { } r ? $" (oggi {Format.Money(r, decimals: 0)})" : "") +
(toReduced ? ", e in reale ridotto su un quarto di esso." : "."));
}
// The simulated twin against the real account (SPEC 12.3): the gap of results, as a share of the capital used.
decimal? twinGap = null;
if (stage.HasTwin && stage.AccountId is { } twinAccount &&
equities.FirstOrDefault(e => e.AccountId == twinAccount && e.Strategy == stage.Strategy) is { Flows: > 0m } twin && equity is { Flows: > 0m } real)
{
twinGap = ((real.Equity - real.Flows) / real.Flows * 100m) - ((twin.Equity - twin.Flows) / twin.Flows * 100m);
}
var requirements = await stages.RequirementsAsync(stage.Strategy, cancellationToken).ConfigureAwait(false);
@@ -126,7 +170,7 @@ internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, bool Li
cards.Add(new StrategyCard(stage, StrategyNames.Label(stage.Strategy, withMarket: true) + (stage.Strategy == StrategyNames.CryptoTrend ? "" : " USA"),
family?.Description ?? "", Rules.GetValueOrDefault(stage.Strategy) ?? [], account.Name ?? "—", account.Currency ?? "EUR", Eur(flows), Eur(result),
flows > 0m ? result / flows * 100m : 0m, worst, trades.Count, trades.Count(r => r >= 0m), symbols, [.. curve.Where(p => p.At >= since || stage.StageSince is null)],
requirements, StageBook.Phrase(stage.Strategy, next), toGo));
requirements, StageBook.Phrase(stage.Strategy, next), toGo, summary, twinGap));
}
var live = accounts.Where(a => a.Environment == TradingEnvironments.Live).Select(a => (a.Id, a.Name, a.Broker)).ToList();
+18 -2
View File
@@ -142,6 +142,10 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets,
public static readonly TimeSpan IdleTimeout = TimeSpan.FromHours(12);
public static readonly TimeSpan MaxLifetime = TimeSpan.FromDays(7);
// Wrong fresh re-authentications (SPEC 12.4) are limited like sign-ins, so a stolen session cannot try passwords.
private const string FreshAttempts = "reauthentication";
private readonly LoginLimiter _fresh = new(clock);
// Each second-factor code works once (RFC 6238, 5.2): the last time step used, in memory.
private readonly Lock _stepGate = new();
private long _lastStep = long.MinValue;
@@ -308,10 +312,16 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets,
/// <summary>
/// The fresh re-authentication of SPEC 12.4: the password and, when it is on, a code from the app, checked right
/// now whatever the session. Nothing is written: a wrong attempt only returns false.
/// now whatever the session. Nothing is written. After five wrong attempts in 15 minutes every attempt fails,
/// even with the right password, until the window has passed.
/// </summary>
public async Task<bool> ReauthenticateAsync(string password, string? code, CancellationToken cancellationToken = default)
{
if (_fresh.Begin(FreshAttempts) > TimeSpan.Zero)
{
return false;
}
var user = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT id, password_hash, totp_secret FROM users WHERE username = @u",
r => (Id: r.Id("id"), Hash: r.Text("password_hash"), Totp: r.BytesOrNull("totp_secret")), ("u", AdminName)), cancellationToken).ConfigureAwait(false);
if (user == default || string.IsNullOrEmpty(password) || !Passwords.Verify(password, user.Hash))
@@ -319,7 +329,13 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets,
return false;
}
return user.Totp is null || AcceptCode(Convert.FromBase64String(secrets.Open("totp:" + user.Id.ToString("D"), user.Totp)), code);
if (user.Totp is null || AcceptCode(Convert.FromBase64String(secrets.Open("totp:" + user.Id.ToString("D"), user.Totp)), code))
{
_fresh.Succeeded(FreshAttempts);
return true;
}
return false;
}
/// <summary>Turning the second factor off asks for both: the password and a code from the app.</summary>
+14
View File
@@ -99,6 +99,12 @@ public static class BacktestReasons
public const string UnknownSymbol = "unknown_symbol";
public const string NoShortSelling = "no_short_selling";
public const string Dividend = "dividend";
/// <summary>
/// Prefix of the notes that count the codes of the correctives and of the risk engine on the intents of each close
/// (<c>adjusted:trade_risk_limit</c>): how often a rule changed what the strategy asked for.
/// </summary>
public const string AdjustedPrefix = "adjusted:";
}
/// <summary>
@@ -371,6 +377,14 @@ public static class BacktestEngine
_history.Add(new EquityMark(day, _cash + invested, invested));
var record = Decide(day, at);
_decisions.Add(record);
foreach (var intent in record.Final)
{
foreach (var code in intent.Adjustments)
{
_notes.Add(new BacktestNote(day, intent.Symbol, BacktestReasons.AdjustedPrefix + code));
}
}
// Exits asked for at this close go now (equity_meanrev's 15:55); the rest waits for the next open.
foreach (var exit in record.Final.Where(i => i.AtClose && i.TargetWeight == 0m))
{
+8 -6
View File
@@ -37,10 +37,11 @@ public static class EuroHistory
}
/// <summary>
/// Divides prices and traded value by the EUR/USD rate of the bar's day, or of the last day before with a rate. A
/// bar is dropped when no rate of the last <see cref="MaxRateAgeDays"/> days exists. The rate of day d is fixed at
/// 16:00 CET, before the daily bar closes at 00:00 UTC, so the close in euro uses nothing from the future. The
/// series stops at the first hole longer than <see cref="MaxGapDays"/> days.
/// Divides prices and traded value by the last EUR/USD rate fixed before the bar opens: the rate of the day before,
/// or of the last day before that with a rate. The rate of day d is fixed at 16:00 CET of d, after the bar of d
/// opens at 00:00 UTC, so using it for that bar's open (where the backtest fills) would read the future. A bar is
/// dropped when no rate of the last <see cref="MaxRateAgeDays"/> days exists. The series stops at the first hole
/// longer than <see cref="MaxGapDays"/> days.
/// </summary>
public static IReadOnlyList<ResearchBar> Convert(IEnumerable<ResearchBar> bars, IReadOnlyList<FxRate> eurUsd)
{
@@ -59,7 +60,7 @@ public static class EuroHistory
previous = bar.OpensAt;
var day = DateOnly.FromDateTime(bar.OpensAt.UtcDateTime);
while (k + 1 < rates.Count && rates[k + 1].Date <= day)
while (k + 1 < rates.Count && rates[k + 1].Date < day)
{
k++;
}
@@ -209,6 +210,7 @@ public static class CryptoTrendProtocol
Verdict = verdict,
Report = ReportPath,
PlanHash = TrialPlan.Hash(main.Plan.ToJson()),
Parameters = main.Report.Variants.FirstOrDefault(v => v.Chosen)?.Parameters,
MaxDrawdown = Math.Round((decimal)main.Report.Metrics.MaxDrawdown, 4),
ExpectedSlippageBp = main.ExpectedSlippageBp,
RoundTripCost = Math.Round(2m * (taker + (main.ExpectedSlippageBp / 10_000m)), 6),
@@ -364,7 +366,7 @@ public static class EquityProtocol
[
"Per provare le strategie sulle azioni servono gli storici giornalieri di Alpaca, con frazionamenti e dividendi, che si scaricano solo con le chiavi di un conto Alpaca (anche dimostrativo). Le chiavi non sono ancora state inserite.",
"Finché manca il backtest la strategia resta in osservazione: guarda il mercato e scrive le sue decisioni nel diario, ma non opera, nemmeno in simulazione.",
"Quando avrai inserito le chiavi nelle Impostazioni, il bot raccoglie gli storici. Poi dal Laboratorio lanci la prova della strategia con l'origine \"barre raccolte\": se supera le soglie di SPEC 12.2, la porti in simulazione dalla pagina Strategie.",
"Quando avrai inserito le chiavi nelle Impostazioni, il bot raccoglie gli storici. Poi il backtest si rifà con gli stessi controlli di crypto_trend e il nuovo esito arriva con un aggiornamento del programma: se supera le soglie, la strategia parte in simulazione da sola al primo avvio dopo l'aggiornamento.",
];
public static Qualification Waiting(string strategy) => new()
+17 -3
View File
@@ -169,17 +169,31 @@ public static class ProtocolReport
b.AppendLine(Text($"| `{v.Parameters}`{(v.Chosen ? " (scelta)" : "")} | {Num(v.Sharpe * annual)} | {Num(v.PlateauScore * annual)} | {Money(v.NetResult, r.Currency)} | {Pct(-v.MaxDrawdown)} | {v.Trades} |"));
}
if (r.Notes.Count > 0)
var adjusted = r.Notes.Where(n => n.Key.StartsWith(BacktestReasons.AdjustedPrefix, StringComparison.Ordinal))
.ToDictionary(n => n.Key[BacktestReasons.AdjustedPrefix.Length..], n => n.Value, StringComparer.Ordinal);
var engine = r.Notes.Where(n => !n.Key.StartsWith(BacktestReasons.AdjustedPrefix, StringComparison.Ordinal)).ToDictionary(n => n.Key, n => n.Value, StringComparer.Ordinal);
void Counts(string title, string what, IReadOnlyDictionary<string, int> counts)
{
b.AppendLine();
b.AppendLine("**Interventi di correttivi e rischio sulla variante scelta**").AppendLine();
b.AppendLine(title).AppendLine();
if (counts.Count == 0)
{
b.AppendLine("Nessuno.");
return;
}
b.AppendLine(what).AppendLine();
b.AppendLine("| Motivo | Volte |").AppendLine("|---|---:|");
foreach (var (reason, count) in r.Notes.OrderByDescending(n => n.Value).ThenBy(n => n.Key, StringComparer.Ordinal))
foreach (var (reason, count) in counts.OrderByDescending(n => n.Value).ThenBy(n => n.Key, StringComparer.Ordinal))
{
b.AppendLine(Text($"| `{reason}` | {count} |"));
}
}
Counts("**Interventi di correttivi e rischio sulla variante scelta**",
"Quante volte, per strumento e giorno, un correttivo o una regola di rischio ha cambiato ciò che la strategia chiedeva.", adjusted);
Counts("**Note del motore di prova**", "Ordini non eseguiti come chiesto: sotto il minimo, residui lasciati dopo un'uscita, liquidità.", engine);
b.AppendLine();
b.AppendLine("**Strumenti**").AppendLine();
b.AppendLine("| Coppia | Prima barra | Ultima barra | Barre |").AppendLine("|---|---|---|---:|");
+53 -20
View File
@@ -133,6 +133,16 @@ public sealed class RiskEngine(Database db, IClock clock, Ledger ledger, StageBo
return (GateResult.Refuse(RiskReasons.Observation), data);
}
// In one account an instrument belongs to one strategy at a time (SPEC 8.6): the other skips the entry.
var otherHolds = (await ledger.PositionsAsync(account.AccountId, cancellationToken).ConfigureAwait(false))
.Any(p => p.InstrumentId == intent.InstrumentId && p.Strategy != intent.Strategy && p.Quantity > 0m);
if (otherHolds || await db.ReadAsync(s => s.CountAsync(
"SELECT COUNT(*) FROM executions WHERE account_id = @a AND instrument_id = @i AND strategy <> @s AND side = 'buy' AND status = @w",
("a", account.AccountId), ("i", intent.InstrumentId), ("s", intent.Strategy), ("w", ExecutionStates.Working)), cancellationToken).ConfigureAwait(false) > 0)
{
return (GateResult.Refuse(RiskReasons.OwnedByOther), data);
}
if (RiskMonitor.EntriesBlocked(risk.State, now))
{
return (GateResult.Refuse(RiskReasons.DailyLossBlock), data);
@@ -182,13 +192,22 @@ public sealed class RiskEngine(Database db, IClock clock, Ledger ledger, StageBo
var quantity = size.Quantity;
var reasons = size.Reasons.ToList();
// No leverage, and a strategy never goes beyond its own capital (SPEC 9.1 point 1, 8.6).
// No leverage, and a strategy never goes beyond its own capital (SPEC 9.1 point 1, 8.6). Purchases already
// under way hold their cash until they fill, and every purchase counts at the highest price its limit may chase
// to (the order-price limit), so several purchases sent together cannot add up to more than the cash.
var cash = (await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false))
.FirstOrDefault(e => e.AccountId == account.AccountId && e.Strategy == intent.Strategy)?.Cash ?? 0m;
var working = await db.ReadAsync(s => s.QueryAsync(
"SELECT quantity, filled, reference_price FROM executions WHERE account_id = @a AND strategy = @s AND side = 'buy' AND status = @w",
r => (r.Money("quantity") - r.Money("filled")) * (r.MoneyOrNull("reference_price") ?? 0m), ("a", account.AccountId), ("s", intent.Strategy),
("w", ExecutionStates.Working)), cancellationToken).ConfigureAwait(false);
var highest = 1m + limits.MaxPriceGap;
var available = cash - (working.Where(v => v > 0m).Sum() * highest);
data["cash"] = cash;
if (quantity * price > cash)
data["reserved"] = cash - available;
if (quantity * price * highest > available)
{
quantity = Math.Max(0m, cash / price);
quantity = Math.Max(0m, available / (price * highest));
reasons.Add(RiskReasons.NoLeverage);
}
@@ -291,7 +310,10 @@ public sealed class RiskEngine(Database db, IClock clock, Ledger ledger, StageBo
{
ArgumentNullException.ThrowIfNull(managers);
await settings.SetAsync(SettingsStore.BotState.Key, "stopped", by, cancellationToken).ConfigureAwait(false);
await RecordAsync(null, reason, RiskSeverities.Critical, message, new { by }, cancellationToken).ConfigureAwait(false);
// A stop is the bot doing its job, not a critical incident of SPEC 12.3 (control of a position or of the books
// lost): it must not hold back a strategy's promotion for 30 days.
await RecordAsync(null, reason, RiskSeverities.High, message, new { by }, cancellationToken).ConfigureAwait(false);
foreach (var manager in managers)
{
await manager.CancelWorkingAsync(reason, cancellationToken: cancellationToken).ConfigureAwait(false);
@@ -378,7 +400,26 @@ public sealed class RiskEngine(Database db, IClock clock, Ledger ledger, StageBo
}
await SaveAsync(BotRow, new BotRiskState(), cancellationToken).ConfigureAwait(false);
await settings.SetAsync(SettingsStore.BotState.Key, "active", by, cancellationToken).ConfigureAwait(false);
// A pause stays a pause: the restart only clears what the switch did.
if ((await settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value == "stopped")
{
await settings.SetAsync(SettingsStore.BotState.Key, "active", by, cancellationToken).ConfigureAwait(false);
}
}
/// <summary>True when the switch of at least one world tripped and waits for the user (SPEC 9.3).</summary>
public async Task<bool> AnyTrippedAsync(CancellationToken cancellationToken)
{
foreach (var world in new[] { Worlds.Simulated, Worlds.Real })
{
if (await LoadAsync<RiskMonitorState>(world, cancellationToken).ConfigureAwait(false) is { Tripped: true })
{
return true;
}
}
return false;
}
/// <summary>
@@ -440,13 +481,14 @@ public sealed class RiskEngine(Database db, IClock clock, Ledger ledger, StageBo
foreach (var stage in all)
{
var carried = await CarriedAsync(stage.Strategy, cancellationToken).ConfigureAwait(false);
total += carried;
// In observation the ledger still holds the strategy's share of the capital entrusted.
total += carried.Carried.Sum(c => Eur(c.Key, c.Value));
// In observation the ledger still holds the strategy's share of the capital entrusted. The ledger taking the
// orders counts from its baseline: what it made before was carried already, or belonged to the twin.
var ledgerAccount = stage.OrdersAccount ?? (stage.Stage == StrategyStages.Observation ? stage.AccountId : null);
if (ledgerAccount is { } account && equities.FirstOrDefault(e => e.AccountId == account && e.Strategy == stage.Strategy) is { } ledgerEquity)
{
var factor = stage.Stage == StrategyStages.Reduced ? 1m / StrategyStages.ReducedShare : 1m;
total += Eur(account, ledgerEquity.Equity) * factor;
total += Eur(account, ledgerEquity.Equity - carried.Baseline(account)) * factor;
counted.Add((account, stage.Strategy));
}
@@ -530,18 +572,9 @@ public sealed class RiskEngine(Database db, IClock clock, Ledger ledger, StageBo
private async Task<HashSet<(Guid, string)>> TwinsAsync(CancellationToken cancellationToken) =>
[.. (await stages.AllAsync(cancellationToken).ConfigureAwait(false)).Where(s => s.HasTwin && s.AccountId is not null).Select(s => (s.AccountId!.Value, s.Strategy))];
private async Task<decimal> CarriedAsync(string strategy, CancellationToken cancellationToken)
{
var json = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT state FROM strategy_state WHERE strategy = @s", r => r.Text("state"), ("s", strategy)), cancellationToken)
.ConfigureAwait(false);
if (json is null)
{
return 0m;
}
using var doc = JsonDocument.Parse(json);
return doc.RootElement.ValueKind == JsonValueKind.Object && doc.RootElement.TryGetProperty("carried_results", out var carried) && carried.TryGetDecimal(out var value) ? value : 0m;
}
private async Task<CarriedResults> CarriedAsync(string strategy, CancellationToken cancellationToken) =>
CarriedResults.Parse(await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT state FROM strategy_state WHERE strategy = @s", r => r.TextOrNull("state"), ("s", strategy)),
cancellationToken).ConfigureAwait(false));
private async Task<decimal?> UsdRateAsync(CancellationToken cancellationToken) =>
(await fx.LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false))?.Rate;
+113 -22
View File
@@ -48,6 +48,12 @@ public sealed record Qualification
public string? PlanHash { get; init; }
/// <summary>
/// The parameters of the variant that qualified, as the report writes them (<c>coin_vol=10;max_stop=20</c>): the
/// strategy runs live with these, so the figures it is compared with are those of the rules it follows.
/// </summary>
public string? Parameters { get; init; }
/// <summary>Largest fall of the backtest, as a fraction of the capital used: 0.18 is −18%.</summary>
public decimal MaxDrawdown { get; init; }
@@ -110,6 +116,36 @@ public sealed class LiveConfirmationException(string code, string message) : Inv
public string Code { get; } = code;
}
/// <summary>
/// The results of the ledgers a strategy worked on, kept in the reference equity (SPEC 9.2) when it changes stage.
/// Each ledger has a baseline: the results already carried, or made while it was not the one taking the orders
/// (the twin's during real money). At a change the ledger being left carries what it made since its baseline,
/// times four from reduced real, and the ledger taking over starts from what it holds now. So a ledger that goes on
/// (reduced to real on the same account, the twin after a demotion) never counts the same result twice. Amounts
/// stay in the ledger's currency and become euro when the reference is computed.
/// </summary>
public sealed record CarriedResults(IReadOnlyDictionary<Guid, decimal> Carried, IReadOnlyDictionary<Guid, decimal> Baselines)
{
public static CarriedResults Empty { get; } = new(new Dictionary<Guid, decimal>(), new Dictionary<Guid, decimal>());
public decimal Baseline(Guid account) => Baselines.TryGetValue(account, out var b) ? b : 0m;
public static CarriedResults Parse(string? state)
{
if (string.IsNullOrEmpty(state) || System.Text.Json.Nodes.JsonNode.Parse(state) is not System.Text.Json.Nodes.JsonObject node)
{
return Empty;
}
static Dictionary<Guid, decimal> Map(System.Text.Json.Nodes.JsonNode? n) =>
n is System.Text.Json.Nodes.JsonObject o
? o.Where(p => Guid.TryParse(p.Key, out _) && p.Value is not null).ToDictionary(p => Guid.Parse(p.Key), p => p.Value!.GetValue<decimal>())
: [];
return new CarriedResults(Map(node["carried"]), Map(node["baselines"]));
}
}
/// <summary>
/// Stages of the strategies (SPEC 12.3, 12.4, 7.1). The only way to real money is <see cref="ConfirmLiveAsync"/>:
/// the startup consent, every requirement met, the confirmation phrase, the password and the second factor checked
@@ -118,6 +154,7 @@ public sealed class LiveConfirmationException(string code, string message) : Inv
/// </summary>
public sealed class StageBook(Database db, IClock clock, TradingConsent consent, Func<string, string?, CancellationToken, Task<bool>> reauthenticate)
{
public const int ObservationDays = 90;
public const int SimulationDays = 60;
public const int ReducedDays = 30;
public const int IncidentDays = 30;
@@ -193,7 +230,9 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent,
{
var current = await s.FirstOrDefaultAsync("SELECT stage, stage_since FROM strategy_state WHERE strategy = @s",
r => (Stage: r.Text("stage"), Since: r.MomentOrNull("stage_since")), ("s", strategy)).ConfigureAwait(false);
if (current == default)
// With real money in play the figures a strategy qualified with do not move (SPEC 12.3): a new build cannot
// change the thresholds of its demotion. It gets the new outcome when it is back in simulation.
if (current == default || StrategyStages.IsLive(current.Stage))
{
return;
}
@@ -241,6 +280,21 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent,
return;
}
// From observation to simulation (SPEC 12.3): the protocol passed on the history and at least 90 days of signals
// collected live. The first start moves a base strategy that passed without this, as the specification says.
if (to == StrategyStages.Simulation && current.Stage == StrategyStages.Observation)
{
if (current.Qualification is not { Passed: true })
{
throw new LiveConfirmationException("backtest", "La strategia non ha superato il protocollo sui dati storici: resta in osservazione.");
}
if (ObservedDays(current) < ObservationDays)
{
throw new LiveConfirmationException("observation", $"Servono almeno {ObservationDays} giorni di segnali raccolti dal vivo in osservazione.");
}
}
await db.WriteAsync(s => MoveCoreAsync(s, strategy, current.Stage, to, reason, by, cancellationToken), cancellationToken).ConfigureAwait(false);
}
@@ -253,6 +307,13 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent,
var list = new List<Requirement>();
var q = stage.Qualification;
list.Add(new("backtest", "Protocollo di verifica sui dati storici", q is null ? "mancante" : q.Passed ? "superato" : "non superato", "superato", q?.Passed == true));
if (stage.Stage == StrategyStages.Observation)
{
var observed = ObservedDays(stage);
list.Add(new("observation", "Giorni di segnali raccolti dal vivo", observed.ToString(Italian), $"almeno {ObservationDays}", observed >= ObservationDays));
return list;
}
if (stage.Stage == StrategyStages.Reduced)
{
var days = (int)(now - since).TotalDays;
@@ -340,7 +401,7 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent,
var now = clock.UtcNow;
await db.WriteAsync(async s =>
{
await CarryResultsAsync(s, stage, cancellationToken).ConfigureAwait(false);
await CarryResultsAsync(s, stage, c.LiveAccountId, cancellationToken).ConfigureAwait(false);
await s.ExecuteAsync("UPDATE strategy_state SET live_account_id = @a, live_confirmed_at = @t, live_confirmed_by = @by, exit_only = @no, updated_at = @t WHERE strategy = @s",
cancellationToken, ("a", c.LiveAccountId), ("t", now), ("by", c.By), ("no", false), ("s", c.Strategy)).ConfigureAwait(false);
await MoveCoreAsync(s, c.Strategy, stage.Stage, to, "confirmed_12_4", c.By, cancellationToken).ConfigureAwait(false);
@@ -375,8 +436,22 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent,
{
throw new LiveConfirmationException("password", "Password o codice non corretti.");
}
// More risk is refused while a strategy with real money has a demotion condition in progress (SPEC 12.4).
foreach (var live in (await AllAsync(cancellationToken).ConfigureAwait(false))
.Where(s => StrategyStages.IsLive(s.Stage) && (broker is null || StrategyNames.BrokerOf(s.Strategy) == broker)))
{
var conditions = await DemotionConditionsAsync(live, cancellationToken).ConfigureAwait(false);
if (conditions.Count > 0 && conditions[0] is var condition)
{
throw new LiveConfirmationException("demotion", $"{StrategyNames.Label(live.Strategy, withMarket: false)} ha una condizione di retrocessione in corso: {condition.Message}.");
}
}
}
private int ObservedDays(StrategyStage stage) =>
stage.Stage == StrategyStages.Observation && stage.StageSince is { } since ? Math.Max(0, (int)(clock.UtcNow - since).TotalDays) : 0;
/// <summary>
/// The user takes real money away from a strategy (SPEC 12.3, 12.4): back to simulation, and the real positions,
/// if any, stay in exit only until they are at zero.
@@ -460,8 +535,12 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent,
list.Add(new("drawdown", $"calo {Format.Percent(worst * 100m, 1)}, oltre 1,5 volte quello del backtest ({Format.Percent(-q.MaxDrawdown * 100m, 1)})"));
}
// Sessions below the 5th percentile of the expected path, counted back from the last day.
var daily = points.GroupBy(p => DateOnly.FromDateTime(p.At.UtcDateTime)).Select(g => g.Last().Index).ToList();
// Sessions below the 5th percentile of the expected path, counted back from the last day. Stocks have no
// session at the weekend: those days are left out, as in the bootstrap of their sessions.
var stocks = StrategyNames.BrokerOf(stage.Strategy) != Anubis.Data.Venues.Okx;
var daily = points.GroupBy(p => DateOnly.FromDateTime(p.At.UtcDateTime))
.Where(g => !stocks || g.Key.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday))
.Select(g => g.Last().Index).ToList();
var start = points[0].Index;
var below = 0;
for (var day = daily.Count - 1; day >= 1 && day - 1 < q.ExpectedPathP5.Count; day--)
@@ -506,7 +585,7 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent,
// management if the strategy is promoted again (SPEC 7.1).
var open = stage.LiveAccountId is { } live && (await s.QueryAsync("SELECT quantity FROM positions WHERE account_id = @a AND strategy = @s",
r => r.Money("quantity"), ("a", live), ("s", strategy)).ConfigureAwait(false)).Any(q => q > 0m);
await CarryResultsAsync(s, stage, cancellationToken).ConfigureAwait(false);
await CarryResultsAsync(s, stage, stage.AccountId, cancellationToken).ConfigureAwait(false);
await s.ExecuteAsync("UPDATE strategy_state SET live_confirmed_at = NULL, live_confirmed_by = NULL, exit_only = @x, updated_at = @t WHERE strategy = @s", cancellationToken,
("x", open), ("t", now), ("s", strategy)).ConfigureAwait(false);
await MoveCoreAsync(s, strategy, stage.Stage, StrategyStages.Simulation, reason, by, cancellationToken).ConfigureAwait(false);
@@ -540,29 +619,41 @@ public sealed class StageBook(Database db, IClock clock, TradingConsent consent,
("id", Ids.NewId(clock)), ("k", "strategy." + strategy + ".stage"), ("o", new DbJson(JsonSerializer.Serialize(from))), ("n", new DbJson(JsonSerializer.Serialize(to))),
("by", by), ("t", clock.UtcNow));
// The results of the ledger a strategy leaves stay in the reference equity (SPEC 9.2): they are carried in its
// state, multiplied by four when they come from reduced real.
private static async Task CarryResultsAsync(DbSession s, StrategyStage stage, CancellationToken cancellationToken)
/// <summary>The results a ledger produced: everything but deposits and withdrawals, open positions at their last price.</summary>
public static async Task<decimal> LedgerResultsAsync(DbSession s, Guid account, string strategy)
{
if (stage.OrdersAccount is not { } account)
{
return;
}
ArgumentNullException.ThrowIfNull(s);
var rows = await s.QueryAsync("SELECT kind, amount FROM cash_ledger WHERE account_id = @a AND strategy = @s",
r => (Kind: r.Text("kind"), Amount: r.Money("amount")), ("a", account), ("s", stage.Strategy)).ConfigureAwait(false);
r => (Kind: r.Text("kind"), Amount: r.Money("amount")), ("a", account), ("s", strategy)).ConfigureAwait(false);
var positions = await s.QueryAsync("SELECT quantity, average_price, last_price FROM positions WHERE account_id = @a AND strategy = @s",
r => r.Money("quantity") * (r.MoneyOrNull("last_price") ?? r.Money("average_price")), ("a", account), ("s", stage.Strategy)).ConfigureAwait(false);
var results = rows.Where(r => !LedgerKinds.IsFlow(r.Kind)).Sum(r => r.Amount) + positions.Sum();
if (stage.Stage == StrategyStages.Reduced)
{
results *= 1m / StrategyStages.ReducedShare;
}
r => r.Money("quantity") * (r.MoneyOrNull("last_price") ?? r.Money("average_price")), ("a", account), ("s", strategy)).ConfigureAwait(false);
return rows.Where(r => !LedgerKinds.IsFlow(r.Kind)).Sum(r => r.Amount) + positions.Sum();
}
private static async Task CarryResultsAsync(DbSession s, StrategyStage stage, Guid? next, CancellationToken cancellationToken)
{
var state = await s.FirstOrDefaultAsync("SELECT state FROM strategy_state WHERE strategy = @s", r => r.Text("state"), ("s", stage.Strategy)).ConfigureAwait(false) ?? "{}";
var node = System.Text.Json.Nodes.JsonNode.Parse(state)?.AsObject() ?? [];
var carried = node["carried_results"]?.GetValue<decimal>() ?? 0m;
node["carried_results"] = DbValues.Money(carried + results);
var current = CarriedResults.Parse(state);
var carried = new Dictionary<Guid, decimal>(current.Carried);
var baselines = new Dictionary<Guid, decimal>(current.Baselines);
if (stage.OrdersAccount is { } leaving)
{
var results = await LedgerResultsAsync(s, leaving, stage.Strategy).ConfigureAwait(false);
var factor = stage.Stage == StrategyStages.Reduced ? 1m / StrategyStages.ReducedShare : 1m;
carried[leaving] = (carried.TryGetValue(leaving, out var c) ? c : 0m) + ((results - current.Baseline(leaving)) * factor);
baselines[leaving] = results;
}
if (next is { } taking && taking != stage.OrdersAccount)
{
baselines[taking] = await LedgerResultsAsync(s, taking, stage.Strategy).ConfigureAwait(false);
}
System.Text.Json.Nodes.JsonObject Write(Dictionary<Guid, decimal> map) =>
new(map.Select(p => KeyValuePair.Create(p.Key.ToString("D"), (System.Text.Json.Nodes.JsonNode?)DbValues.Money(p.Value))));
node["carried"] = Write(carried);
node["baselines"] = Write(baselines);
await s.ExecuteAsync("UPDATE strategy_state SET state = @j WHERE strategy = @s", cancellationToken, ("j", new DbJson(node.ToJsonString())), ("s", stage.Strategy)).ConfigureAwait(false);
}
+13 -11
View File
@@ -21,18 +21,20 @@ public sealed class ProtocolTests
private static FxRate Usd(DateOnly day, decimal rate) => new("EUR", "USD", day, rate, "ecb");
[TestMethod]
public void UsdtPricesBecomeEurosWithTheRateOfTheDayOrTheLastBefore()
public void UsdtPricesBecomeEurosWithTheLastRateFixedBeforeTheBarOpens()
{
var friday = new DateOnly(2024, 3, 1);
var bars = new[] { Bar(friday, 110m), Bar(friday.AddDays(1), 120m), Bar(friday.AddDays(3), 100m) };
var rates = new[] { Usd(friday, 1.10m), Usd(friday.AddDays(3), 1.25m) };
var thursday = new DateOnly(2024, 2, 29);
var friday = thursday.AddDays(1);
var bars = new[] { Bar(friday, 110m), Bar(friday.AddDays(1), 120m), Bar(friday.AddDays(3), 100m), Bar(friday.AddDays(4), 125m) };
var rates = new[] { Usd(thursday, 1.10m), Usd(friday, 1.20m), Usd(friday.AddDays(3), 1.25m) };
var euro = EuroHistory.Convert(bars, rates);
Assert.HasCount(3, euro);
Assert.AreEqual(100m, euro[0].Close);
Assert.AreEqual(109.090909090909m, euro[1].Close); // Saturday: Friday's rate.
Assert.AreEqual(80m, euro[2].Close);
Assert.HasCount(4, euro);
Assert.AreEqual(100m, euro[0].Close, "Friday's bar opens before Friday's rate is fixed: Thursday's");
Assert.AreEqual(100m, euro[1].Close); // Saturday: Friday's rate.
Assert.AreEqual(83.333333333333m, euro[2].Close); // Monday: still Friday's, Monday's comes in the afternoon.
Assert.AreEqual(100m, euro[3].Close); // Tuesday: Monday's.
Assert.AreEqual(100m, euro[0].Volume, "the volume is in coins: it does not change");
Assert.AreEqual(10_000m, euro[0].QuoteVolume);
Assert.AreEqual("BTCEUR", EuroHistory.SymbolOf("BTCUSDT"));
@@ -46,8 +48,8 @@ public sealed class ProtocolTests
var euro = EuroHistory.Convert(bars, [Usd(day, 1m)]);
Assert.HasCount(EuroHistory.MaxRateAgeDays + 1, euro, "before the first rate and after a week without rates there is no price in euro");
Assert.AreEqual(day, DateOnly.FromDateTime(euro[0].OpensAt.UtcDateTime));
Assert.HasCount(EuroHistory.MaxRateAgeDays, euro, "up to the first rate and after a week without rates there is no price in euro");
Assert.AreEqual(day.AddDays(1), DateOnly.FromDateTime(euro[0].OpensAt.UtcDateTime));
Assert.AreEqual(day.AddDays(EuroHistory.MaxRateAgeDays), DateOnly.FromDateTime(euro[^1].OpensAt.UtcDateTime));
}
@@ -56,7 +58,7 @@ public sealed class ProtocolTests
{
var day = new DateOnly(2022, 5, 10);
var bars = new[] { Bar(day, 1m), Bar(day.AddDays(1), 0.0001m), Bar(day.AddDays(1 + EuroHistory.MaxGapDays + 1), 5m), Bar(day.AddDays(2 + EuroHistory.MaxGapDays + 1), 6m) };
var rates = Enumerable.Range(0, 20).Select(i => Usd(day.AddDays(i), 1m)).ToList();
var rates = Enumerable.Range(-1, 21).Select(i => Usd(day.AddDays(i), 1m)).ToList();
var euro = EuroHistory.Convert(bars, rates);
+111 -3
View File
@@ -157,9 +157,10 @@ public sealed class RiskEngineTests
Assert.IsTrue(row.Data!.ContainsKey("reference"));
// No leverage: with the rest of the bot ten times larger the limits allow more, the strategy's own cash does not.
// The purchase counts at the highest price its limit may chase to.
await s.Rig.Ledger.RecordCapitalAsync(s.Account.AccountId, "sma_cross", 90_000m, "EUR", "test", _none);
var poor = await s.Risk.GateAsync(Buy(s, 0.5m), s.Account, _none);
Assert.AreEqual(Math.Round(10_000m / 60_010m, 8), Math.Round(poor.Quantity, 8));
Assert.AreEqual(Math.Round(10_000m / (60_010m * (1m + RiskLimits.Default.MaxPriceGap)), 8), Math.Round(poor.Quantity, 8));
Assert.AreEqual(RiskReasons.NoLeverage, poor.Reasons[^1]);
}
@@ -251,7 +252,7 @@ public sealed class RiskEngineTests
Assert.IsFalse(world.State.Tripped);
Assert.AreEqual(0m, world.Measures.Drawdown, "the high starts again from now");
Assert.AreEqual("active", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
Assert.IsNotEmpty(await s.Rig.QueryAsync("SELECT key FROM config_history WHERE key = @k AND changed_by = 'utente'", r => r.Text("key"), ("k", SettingsStore.BotState.Key)));
Assert.AreEqual(RiskSeverities.Info, (await EventsAsync(s.Rig, "restart")).Single(), "the restart is recorded with who confirmed it");
}
[TestMethod]
@@ -278,7 +279,8 @@ public sealed class RiskEngineTests
await OrdersAsync(1, "exit");
await s.Risk.CheckAsync([], _none);
Assert.AreEqual("stopped", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
Assert.AreEqual(RiskSeverities.Critical, (await EventsAsync(s.Rig, RiskReasons.OrdersPerMinute)).Single());
// A stop is not a critical incident of SPEC 12.3: it must not hold back a promotion for 30 days.
Assert.AreEqual(RiskSeverities.High, (await EventsAsync(s.Rig, RiskReasons.OrdersPerMinute)).Single());
}
[TestMethod]
@@ -553,4 +555,110 @@ public sealed class RiskEngineTests
Assert.AreEqual(2_500m, exposure.RealEquity);
Assert.AreEqual(10_000m, await s.Risk.ReferenceAsync(_none));
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheReferenceCountsEachResultOnceAcrossStageChanges()
{
await using var s = await CreateAsync(Consent());
var live = await s.Rig.AccountAsync(Venues.Okx, TradingEnvironments.Live, "OKX reale (finto)");
async Task TradeAsync(AccountContext account, decimal quantity, decimal sold)
{
await s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(account, s.Btc, StrategyNames.CryptoTrend, OrderSide.Buy, quantity, 60_000m), _none);
await s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(account, s.Btc, StrategyNames.CryptoTrend, OrderSide.Sell, quantity, sold), _none);
}
Task<decimal> ResultsAsync(AccountContext account) => s.Rig.Db.ReadAsync(x => StageBook.LedgerResultsAsync(x, account.AccountId, StrategyNames.CryptoTrend), _none);
// In simulation: the capital and what the simulation made.
await TradeAsync(s.Account, 0.1m, 70_000m);
var simulated = await ResultsAsync(s.Account);
Assert.AreEqual(10_000m + simulated, await s.Risk.ReferenceAsync(_none));
// Reduced real: the simulation's results stay, the quarter on the real account counts four times.
await RequirementsMetAsync(s);
await s.Rig.Ledger.RecordCapitalAsync(live.AccountId, StrategyNames.CryptoTrend, 2_500m, "EUR", "test", _none);
await s.Stages.ConfirmLiveAsync(new LiveConfirmation(StrategyNames.CryptoTrend, live.AccountId, StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Reduced),
Password, null, "utente"), _none);
await TradeAsync(live, 0.01m, 66_000m);
var reduced = await ResultsAsync(live);
await TradeAsync(s.Account, 0.05m, 50_000m); // the twin's results are not part of the reference
Assert.AreEqual(10_000m + simulated + (4m * reduced), await s.Risk.ReferenceAsync(_none));
// Real, on the same ledger: what was made in reduced is counted once, four times, not five.
s.Rig.Clock.Advance(TimeSpan.FromDays(31));
await s.Rig.Ledger.RecordCapitalAsync(live.AccountId, StrategyNames.CryptoTrend, 7_500m, "EUR", "test", _none);
await s.Stages.ConfirmLiveAsync(new LiveConfirmation(StrategyNames.CryptoTrend, live.AccountId, StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Real),
Password, null, "utente"), _none);
Assert.AreEqual(10_000m + simulated + (4m * reduced), await s.Risk.ReferenceAsync(_none));
// Back to simulation: the simulation's old results are not counted again, nor the twin's.
await s.Stages.RevokeAsync(StrategyNames.CryptoTrend, "utente", "user", _none);
Assert.AreEqual(10_000m + simulated + (4m * reduced), await s.Risk.ReferenceAsync(_none));
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task AnInstrumentBelongsToOneStrategyPerAccountAndPurchasesUnderWayHoldTheirCash()
{
await using var s = await CreateAsync();
// SPEC 8.6: another strategy holds BTC in this account, crypto_trend skips the entry.
await s.Rig.Ledger.RecordCapitalAsync(s.Account.AccountId, "sma_cross", 10_000m, "EUR", "test", _none);
await HoldAsync(s, s.Account, 0.01m, "sma_cross");
Assert.AreEqual(RiskReasons.OwnedByOther, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal);
await s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(s.Account, s.Btc, "sma_cross", OrderSide.Sell, 0.01m, 60_000m), _none);
Assert.IsNull((await s.Risk.GateAsync(Buy(s, 0.001m), s.Account, _none)).Refusal);
// A purchase of 9 600 € still under way holds its cash: only what is left can be bought, at the highest price.
await s.Rig.Db.WriteAsync(x => x.ExecuteAsync(
"INSERT INTO executions (id, account_id, instrument_id, strategy, side, purpose, quantity, filled, order_key, sequence, step, reference_price, status, started_at, created_at, updated_at) " +
"VALUES (@id, @a, @i, @s, 'buy', 'entry', 0.16, 0, 'K1', 1, 0, 60000, @w, @t, @t, @t)", _none,
("id", Ids.NewId(s.Rig.Clock)), ("a", s.Account.AccountId), ("i", s.Btc.Id), ("s", StrategyNames.CryptoTrend), ("w", ExecutionStates.Working), ("t", s.Rig.Clock.UtcNow)), _none);
var highest = 1m + RiskLimits.Default.MaxPriceGap;
var result = await s.Risk.GateAsync(Buy(s, 0.5m), s.Account, _none);
Assert.AreEqual(RiskReasons.NoLeverage, result.Reasons[^1]);
Assert.IsLessThanOrEqualTo(10_000m - (9_600m * highest) + 0.01m, result.Quantity * 60_010m * highest);
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task ObservationLastsNinetyDaysBeforeTheSimulation()
{
await using var s = await CreateAsync();
await s.Rig.Db.WriteAsync(x => x.ExecuteAsync("UPDATE strategy_state SET stage = 'observation', stage_since = @t", _none, ("t", s.Rig.Clock.UtcNow)), _none);
var passed = new Qualification { Passed = true, Verdict = "superato", Report = "docs/backtests/crypto_trend.md" };
await s.Stages.ApplyQualificationAsync(StrategyNames.CryptoTrend, passed with { Passed = false, Verdict = "non superato" }, _none);
// SPEC 12.3: the protocol passed and 90 days of signals collected live.
var refused = await Assert.ThrowsExactlyAsync<LiveConfirmationException>(() => s.Stages.MoveAsync(StrategyNames.CryptoTrend, StrategyStages.Simulation, "user", "utente", _none));
Assert.AreEqual("backtest", refused.Code);
// A new outcome after the first start: written as the first start would, without its automatic move.
await s.Rig.Db.WriteAsync(x => x.ExecuteAsync("UPDATE strategy_state SET qualification = @q", _none,
("q", new DbJson(System.Text.Json.JsonSerializer.Serialize(passed, Qualification.Json)))), _none);
s.Rig.Clock.Advance(TimeSpan.FromDays(89));
refused = await Assert.ThrowsExactlyAsync<LiveConfirmationException>(() => s.Stages.MoveAsync(StrategyNames.CryptoTrend, StrategyStages.Simulation, "user", "utente", _none));
Assert.AreEqual("observation", refused.Code);
var requirement = (await s.Stages.RequirementsAsync(StrategyNames.CryptoTrend, _none)).Single(r => r.Key == "observation");
Assert.IsFalse(requirement.Met);
s.Rig.Clock.Advance(TimeSpan.FromDays(1));
await s.Stages.MoveAsync(StrategyNames.CryptoTrend, StrategyStages.Simulation, "user", "utente", _none);
Assert.AreEqual(StrategyStages.Simulation, (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!.Stage);
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task WithRealMoneyTheQualificationDoesNotMove()
{
await using var s = await CreateAsync(Consent());
var live = await s.Rig.AccountAsync(Venues.Okx, TradingEnvironments.Live, "OKX reale (finto)");
await RequirementsMetAsync(s);
await s.Stages.ConfirmLiveAsync(new LiveConfirmation(StrategyNames.CryptoTrend, live.AccountId, StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Reduced),
Password, null, "utente"), _none);
// SPEC 12.3: a new build cannot move the figures a strategy with real money is compared with.
await s.Stages.ApplyQualificationAsync(StrategyNames.CryptoTrend, new Qualification { Passed = true, Verdict = "altro", Report = "altro.md", MaxDrawdown = 0.50m }, _none);
Assert.AreEqual(0.20m, (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!.Qualification!.MaxDrawdown);
}
}
+21
View File
@@ -293,4 +293,25 @@ public sealed class AccessTests
var history = await new SettingsStore(test.Db, clock, new EventBus()).HistoryAsync().ConfigureAwait(false);
CollectionAssert.IsSubsetOf(new[] { "security.password", "security.second_factor" }, history.Select(h => h.Key).Distinct().ToList());
}
[TestMethod]
[TestCategory(Category.Integration)]
public async Task TheFreshPasswordOfTheProcedureStopsAfterFiveWrongAttempts()
{
// SPEC 12.4: a stolen session must not be able to try passwords on the confirmation forms.
var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero));
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
var access = new AccessStore(test.Db, clock, new SecretStore(test.Db, clock, new byte[32]), iterations: 1000);
Assert.IsTrue(await access.EnsureUserAsync("password-giusta", mustChange: false).ConfigureAwait(false));
Assert.IsTrue(await access.ReauthenticateAsync("password-giusta", null).ConfigureAwait(false));
for (var i = 0; i < LoginLimiter.PerAddress; i++)
{
Assert.IsFalse(await access.ReauthenticateAsync("sbagliata-" + i, null).ConfigureAwait(false));
}
Assert.IsFalse(await access.ReauthenticateAsync("password-giusta", null).ConfigureAwait(false), "even the right password waits");
clock.Advance(LoginLimiter.Window);
Assert.IsTrue(await access.ReauthenticateAsync("password-giusta", null).ConfigureAwait(false));
}
}
@@ -1,4 +1,5 @@
using System.Net;
using System.Net.Http.Json;
using Anubis.Core;
using Anubis.Db;
using Anubis.Risk;
@@ -95,6 +96,17 @@ public sealed class StrategyScreensTests
var services = server.Host.Services!;
var daily = RiskSettings.DailyLoss.Key;
// Not through the API: there the order of the limits and the procedure of SPEC 12.4 would be skipped.
var csrf = await server.Http.GetFromJsonAsync<Dictionary<string, string>>(new Uri("/api/antiforgery", UriKind.Relative));
using (var request = new HttpRequestMessage(HttpMethod.Put, new Uri("/api/settings/" + RiskSettings.DrawdownStop.Key, UriKind.Relative)) { Content = JsonContent.Create(new { value = "40" }) })
{
request.Headers.Add(csrf!["header"], csrf["token"]);
using var put = await server.Http.SendAsync(request);
Assert.AreEqual(HttpStatusCode.BadRequest, put.StatusCode);
}
Assert.AreEqual("15", (await services.Settings.GetAsync(RiskSettings.DrawdownStop.Key, CancellationToken.None)).Value);
// Out of range, or the halving after the switch: nothing changes.
using (var wrong = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "50")))
{
@@ -175,5 +187,19 @@ public sealed class StrategyScreensTests
}
Assert.AreEqual("active", await StateAsync());
// The switch tripped by itself in the simulation: the bot stays "active" elsewhere, and the page offers the restart.
await services.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO risk_state (id, world, state, created_at, updated_at) VALUES (@id, 'simulated', @j, @t, @t)",
CancellationToken.None, ("id", Guid.NewGuid()), ("j", new DbJson("{\"tripped\":true}")), ("t", DateTimeOffset.UtcNow)), CancellationToken.None);
var page = await server.TextAsync("/rischio");
StringAssert.Contains(page, "Interruttore scattato nel mondo simulato");
StringAssert.Contains(page, "Riparti");
using (var again = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva", ("ritorno", "/rischio")))
{
Assert.IsFalse(ServerHarness.Location(again).Contains("errore", StringComparison.Ordinal), ServerHarness.Location(again));
}
Assert.IsFalse(await services.Trading.Risk.AnyTrippedAsync(CancellationToken.None));
Assert.AreEqual("active", await StateAsync());
}
}