diff --git a/.dockerignore b/.dockerignore
index cf448c2..baa4069 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -7,6 +7,7 @@ artifacts/
TestResults/
docs/
!docs/design/logo/
+!docs/backtests/*.outcome.json
**/*.md
.env
.env.*
diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile
index d0a17b6..f1bc33a 100644
--- a/deploy/docker/Dockerfile
+++ b/deploy/docker/Dockerfile
@@ -11,6 +11,8 @@ COPY src/Anubis/ src/Anubis/
COPY src/Anubis.Server/ src/Anubis.Server/
# The logo is embedded from docs/design/logo, its only source (ADR 0005).
COPY docs/design/logo/ docs/design/logo/
+# The backtest outcomes are read at the first start (SPEC 12.3); .dockerignore lets only their JSON files through.
+COPY docs/backtests/ docs/backtests/
RUN dotnet publish src/Anubis.Server/Anubis.Server.csproj -c Release --no-restore -o /app
FROM mcr.microsoft.com/dotnet/aspnet:10.0
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index ee7959f..f43a54c 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -156,25 +156,25 @@ Le tre strategie di base dentro un motore del rischio che nessuno può aggirare.
**Lavori**
-- [ ] [#38](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/38) Strategia `crypto_trend`
-- [ ] [#39](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/39) Strategia `equity_momentum`
-- [ ] [#40](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/40) Strategia `equity_meanrev`
-- [ ] [#41](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/41) Correttivi comuni, ripartizione del capitale e dimensionamento
-- [ ] [#42](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/42) Motore del rischio completo con interruttore d'emergenza
-- [ ] [#43](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/43) Stadi delle strategie, requisiti, gemello simulato, sola uscita e conferma per i soldi veri
-- [ ] [#44](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/44) Backtest onesti delle tre strategie in docs/backtests/
-- [ ] [#45](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/45) Schermate Strategie, Rischio e Operazioni con la scheda "perché"; Impostazioni su strategie, limiti e scenari
-- [ ] [#46](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/46) Chiusura della fase, revisione indipendente e tag `fase-5`
+- [x] [#38](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/38) Strategia `crypto_trend`
+- [x] [#39](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/39) Strategia `equity_momentum`
+- [x] [#40](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/40) Strategia `equity_meanrev`
+- [x] [#41](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/41) Correttivi comuni, ripartizione del capitale e dimensionamento
+- [x] [#42](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/42) Motore del rischio completo con interruttore d'emergenza
+- [x] [#43](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/43) Stadi delle strategie, requisiti, gemello simulato, sola uscita e conferma per i soldi veri
+- [x] [#44](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/44) Backtest onesti delle tre strategie in docs/backtests/
+- [x] [#45](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/45) Schermate Strategie, Rischio e Operazioni con la scheda "perché"; Impostazioni su strategie, limiti e scenari
+- [x] [#46](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/46) Chiusura della fase, revisione indipendente e tag `fase-5`
**Criteri di accettazione**
-- [ ] Ogni regola di 9.1 e 9.2 ha il suo test
-- [ ] Un test dimostra che senza la procedura di 12.4 nessun ordine raggiunge un conto reale
-- [ ] Un test dimostra che una strategia retrocessa continua a gestire uscite e stop delle sue posizioni reali fino a zero
-- [ ] 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
-- [ ] Senza chiavi Alpaca i backtest azionari restano in attesa dell'utente e le due strategie azionarie restano in osservazione
-- [ ] I test anti-sguardo-avanti passano
-- [ ] Le schermate Strategie, Rischio e Operazioni corrispondono ai mockup
+- [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 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)
## Fase 6 — Motore dal vivo in simulazione
diff --git a/docs/STATE.md b/docs/STATE.md
index 535414c..97e78b9 100644
--- a/docs/STATE.md
+++ b/docs/STATE.md
@@ -4,7 +4,7 @@ Aggiornato: 2026-11-11
## Fase corrente
-**Fase 4 — Backtest e laboratorio: completata.** La prossima è la Fase 5 (Strategie, portafoglio, rischio), da iniziare con il via dell'utente. Restano in attesa delle chiavi demo di OKX e di Alpaca le prove sui conti di prova (Fase 3) e lo storico azionario (Fase 2).
+**Fase 5 — Strategie, portafoglio, rischio: completata.** La prossima è la Fase 6 (Motore dal vivo in simulazione), da iniziare con il via dell'utente. Nessuna delle tre strategie è ancora in simulazione: `crypto_trend` non ha superato il backtest e le due azionarie aspettano le chiavi di Alpaca. Restano in attesa delle chiavi demo di OKX e di Alpaca anche le prove sui conti di prova (Fase 3) e lo storico azionario (Fase 2).
## Fatto
@@ -70,6 +70,13 @@ Aggiornato: 2026-11-11
- Laboratorio su un thread a priorità bassa, una prova alla volta, con ripresa dopo un riavvio; dati dalle barre raccolte o dallo storico di ricerca Binance.
- Schermata Laboratorio: elenco delle prove, modulo per un nuovo test, rapporto completo, confronto tra due prove. Le sezioni "Migliorie in osservazione" e "Stime di costo da confermare" aspettano le Fasi 9 e 8.
- Strategia d'esempio `sma_cross` (incrocio di medie) per provare il laboratorio; le strategie di base arrivano con la Fase 5.
+- **Fase 5** (scelte nell'ADR 0011):
+ - Le tre strategie di base: `crypto_trend` (rottura su nove periodi, stop a metà del canale, pesi a volatilità obiettivo, universo dei primi dieci del mese), `equity_momentum` (revisione settimanale con il filtro di SPY, pesi a volatilità inversa, stop che segue il prezzo) e `equity_meanrev` (RSI a 2 sopra la media a 200 sedute, rischio fisso, uscita alla chiusura). Le stesse classi girano in prova e dal vivo e passano il test contro lo sguardo in avanti.
+ - 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 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
@@ -77,7 +84,7 @@ Nulla.
## Prossimo passo
-Fase 5, strategie, portafoglio e rischio: le tre strategie di base, i correttivi, la ripartizione del capitale e il motore del rischio completo, con i backtest onesti di ciascuna strategia fatti nel Laboratorio. Con le chiavi dei conti di prova si possono chiudere i due criteri in attesa (azioni della Fase 2, conti di prova della Fase 3).
+Fase 6, motore dal vivo in simulazione: l'orchestrazione della giornata, il processo di guardia, il recupero dopo un'assenza, il Diario, Panoramica, Telegram e la prova di durata di 48 ore. Con le chiavi del conto paper di Alpaca si possono fare i backtest azionari (`anubis backtest base`) e chiudere i criteri in attesa delle Fasi 2 e 3.
## Da sapere
@@ -88,7 +95,10 @@ Fase 5, strategie, portafoglio e rischio: le tre strategie di base, i correttivi
- `tasks dev` fuori da Docker usa la cartella dei dati vera dell'utente: per prove usa `tasks seed-demo`.
- Alpaca non ha più conti senza margine: il divieto di leva lo impone Anubis (API-NOTES A14).
- 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, senza convertirli: una prova lavora in una sola valuta (ADR 0010, punto 13).
+- 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.
- Gli universi passati usano i flag ETF e "frazionabile" di oggi: è un limite delle fonti gratuite (API-NOTES, Fase 2).
@@ -99,8 +109,8 @@ Fase 5, strategie, portafoglio e rischio: le tre strategie di base, i correttivi
| Cosa | Da quando serve | Senza |
|---|---|---|
-| Via libera per la Fase 5 | Subito | Non si parte |
-| Chiavi del conto paper di Alpaca (`ALPACA_API_KEY_DEMO`, `ALPACA_API_SECRET_DEMO`) | Già dalla Fase 2 (dati azionari) | Parte azionaria spenta; storico azionario dal 2016 in attesa |
+| Via libera per la Fase 6 | Subito | Non si parte |
+| Chiavi del conto paper di Alpaca (`ALPACA_API_KEY_DEMO`, `ALPACA_API_SECRET_DEMO`) | Già dalla Fase 2 (dati azionari) | Parte azionaria spenta; storico azionario dal 2016 e backtest delle due strategie azionarie in attesa |
| Chiavi demo di OKX Europe, senza permesso di prelievo | Fase 3 (ordini sui conti di prova) | Batteria di conformità su risposte d'esempio; criterio della Fase 3 in attesa |
| Un token Gitea con permesso `write:package` come segreto `REGISTRY_TOKEN` | Fase 9 (pubblicazione dell'immagine) | Pubblicazione a mano |
| Token del bot Telegram e chat autorizzata (facoltativi) | Fase 6 | Test con un finto server |
diff --git a/docs/adr/0011-scelte-fase-5.md b/docs/adr/0011-scelte-fase-5.md
new file mode 100644
index 0000000..787f4c7
--- /dev/null
+++ b/docs/adr/0011-scelte-fase-5.md
@@ -0,0 +1,90 @@
+# 0011 — Scelte della Fase 5: strategie, portafoglio, rischio
+
+Data: 2026-11-11 · Stato: accettata · Precisa la specifica (sezioni 7.1, 7.5, 8, 9, 12, 13.1–13.6) e l'ADR 0010, senza aggiungere componenti esterni
+
+## Contesto
+
+La Fase 5 porta le tre strategie di base, i correttivi comuni, il motore del rischio, gli stadi verso i soldi veri, i backtest onesti delle strategie e le schermate Operazioni, Strategie e Rischio. Alcune scelte non sono scritte nella specifica, o la precisano. Le raccolgo qui.
+
+## Decisione
+
+**1. Le strategie sono le stesse in prova e dal vivo.**
+- Le tre strategie (`crypto_trend`, `equity_momentum`, `equity_meanrev`) sono classi senza stato proprio: leggono le barre, il loro portafoglio e il patrimonio di riferimento, e restituiscono intenzioni (peso voluto e stop). Ogni intenzione ha un codice motivo, mai un testo libero.
+- Il motore di backtest ha imparato ciò che le regole chiedono: l'uscita alla stessa chiusura (`equity_meanrev`, che dal vivo vende alle 15:55), lo stop messo a una distanza dal prezzo ottenuto, gli strumenti di solo dato come SPY, il calendario di borsa e la storia del patrimonio.
+- Il patrimonio di riferimento di una strategia è quello della sua quota del bot (`ReferenceShare`): i limiti in percentuale si misurano sul bot, non sulla sola strategia.
+- Tutte e tre passano il test contro lo sguardo in avanti dell'ADR 0010 (punto 11).
+
+**2. Correttivi e rischio girano anche nei backtest.** I correttivi di 8.5 (regime crypto: metà delle nuove entrate quando Bitcoin chiude sotto la media a 200 giorni o la sua volatilità supera il 90° percentile di due anni; calendario economico: niente entrate da 30 minuti prima a 30 dopo un dato USA importante, fino a 60 dopo una decisione di Fed o BCE) e le regole di 9.1 e 9.2 sono passi della decisione, gli stessi dal vivo e in prova. Nel backtest di una strategia:
+- la strategia è una parte del bot e il resto conta come liquidità ferma, così una sua perdita pesa sul mondo quanto la sua quota;
+- ogni chiusura è una giornata italiana a sé (mezzogiorno UTC);
+- dopo che l'interruttore scatta si suppone che l'utente riparta una settimana dopo, e il massimo si misura da lì;
+- età del prezzo, prezzo dell'ordine e orologio esistono solo dal vivo.
+
+**3. Il motore del rischio toglie o riduce, mai aggiunge.**
+- Ogni intenzione lo attraversa prima di diventare un ordine; la protezione (stop e uscite) passa sempre.
+- Le tre misure di 9.2 (perdita del giorno da mezzanotte italiana, degli ultimi sette giorni, calo dal massimo) vengono dall'indice ponderato nel tempo di ciascun mondo, così versamenti e prelievi non sembrano guadagni o perdite. Simulato e reale sono due mondi: un limite ferma solo il mondo dove è stato superato.
+- Il monitor è una macchina a stati pura, la stessa in prova e dal vivo, e il suo moltiplicatore è sempre uno o meno.
+- L'avviso parte all'80% di una soglia, una volta per superamento, senza blocchi.
+- La protezione per le operazioni in giornata (`pdt_guard`) è spenta in partenza: Anubis non usa il margine.
+- I test di proprietà controllano che il risultato non sia mai più grande del richiesto, e mai più grande dopo una perdita.
+
+**4. Fermare e ripartire passa sempre dal motore del rischio.** "Ferma tutto", "Ferma e chiudi", il file `STOP` nella cartella dei dati e l'anomalia di ordini al minuto fermano il bot finché l'utente non conferma la ripartenza. La ripartenza è rifiutata finché il file `STOP` esiste. Dopo uno scatto il massimo si misura dalla ripartenza.
+
+**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. 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 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. 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.
+
+**9. I risultati per strategia si arrotondano come in Conti.** Ogni posizione si arrotonda al centesimo prima di sommare, così Strategie e Conti mostrano lo stesso numero.
+
+**10. Lo storico crypto in euro, per i backtest delle strategie.** L'ADR 0010 (punto 13) lasciava i dati Binance in USDT; per le strategie di base serve l'euro, perché il bot pensa in euro.
+- 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.**
+- Periodo dal 01/01/2019 al 31/10/2026. Le prove leggono anche 450 giorni prima dell'inizio (`TrialData.WarmupDays`), solo perché indicatori ed età minima di quotazione (400 giorni) siano pronti dal primo giorno. Il controllo "strumento vuoto" e il conteggio delle sedute guardano solo dentro il periodo.
+- `crypto_trend` si prova su due universi: quello largo e solo BTC, ETH e SOL. Supera solo se superano entrambi; le misure mostrate vengono dall'universo largo.
+- Nel DSR il secondo universo conta come prove precedenti anche le varianti del primo. L'id della prova viene dall'impronta del piano, così rifare il calcolo non crea prove nuove.
+- Per gli strumenti dell'universo largo il limite del Laboratorio sale a 60 (`Laboratory.MaxSymbols`).
+- 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 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.
+
+## Conseguenze
+
+- Nessuna strategia può arrivare alla simulazione senza un backtest superato, né ai soldi veri senza la procedura di 12.4. Oggi tutte e tre restano in osservazione: è l'esito onesto, non un difetto.
+- Le prove dei backtest azionari partono quando l'utente fornisce le chiavi del conto paper di Alpaca.
+- Cambiare una regola di `crypto_trend` per farla passare richiede una nuova versione della strategia e una nuova prova, che il DSR conterà insieme a quelle già fatte.
diff --git a/docs/backtests/crypto_trend.md b/docs/backtests/crypto_trend.md
new file mode 100644
index 0000000..bf04409
--- /dev/null
+++ b/docs/backtests/crypto_trend.md
@@ -0,0 +1,286 @@
+# Backtest di `crypto_trend` (Trend crypto)
+
+**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.
+
+Per rifarlo: `anubis backtest base --to 2026-10-31`. Il file dell'esito, letto dal bot al primo avvio, è `docs/backtests/crypto_trend.outcome.json`.
+
+## Dati
+
+- Archivi giornalieri di data.binance.vision in USDT, ogni file controllato con la sua impronta SHA-256 prima dell'uso.
+- Prezzi convertiti in euro con il cambio EUR/USD della BCE del giorno (7133 giorni di cambi), contando un USDT come un dollaro. Le coppie in euro di OKX esistono solo da novembre 2023: questo storico è un'approssimazione (SPEC 8.1).
+- 47 coppie nell'universo ampio, comprese quelle poi chiuse da Binance: ogni mese la strategia sceglie le 10 con più scambi tra quelle quotate da almeno 400 giorni.
+- Lo spread non si può misurare su questo storico: il filtro dello spread vale solo dal vivo.
+- Senza archivi nel periodo, quindi non usate: BCCEUR, VENEUR.
+
+## Riepilogo
+
+| Prova | Variante scelta | Rendimento annuo | Calo massimo | Netto a costi doppi | DSR | PBO | Esito |
+|---|---|---:|---:|---:|---:|---:|---|
+| 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: −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 `b5f566d59bfa`, dei dati `840015607150`.
+
+| | Strategia | Comprare e tenere |
+|---|---:|---:|
+| 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,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 | 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 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 | 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,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 |
+|---|---:|
+| `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**
+
+| Coppia | Prima barra | Ultima barra | Barre |
+|---|---|---|---:|
+| ADAEUR | 2018-04-17 | 2026-10-31 | 3120 |
+| APEEUR | 2022-03-17 | 2026-10-31 | 1690 |
+| ARBEUR | 2023-03-23 | 2026-10-31 | 1319 |
+| ATOMEUR | 2019-04-29 | 2026-10-31 | 2743 |
+| AVAXEUR | 2020-09-22 | 2026-10-31 | 2231 |
+| BCHABCEUR | 2018-11-16 | 2019-11-28 | 378 |
+| BCHEUR | 2019-11-28 | 2026-10-31 | 2530 |
+| BCHSVEUR | 2018-11-16 | 2019-04-22 | 158 |
+| BNBEUR | 2017-11-06 | 2026-10-31 | 3282 |
+| BTCEUR | 2017-10-08 | 2026-10-31 | 3311 |
+| DASHEUR | 2019-03-28 | 2026-10-31 | 2775 |
+| DOGEEUR | 2019-07-05 | 2026-10-31 | 2676 |
+| DOTEUR | 2020-08-18 | 2026-10-31 | 2266 |
+| EOSEUR | 2018-05-28 | 2025-05-26 | 2556 |
+| ETCEUR | 2018-06-12 | 2026-10-31 | 3064 |
+| ETHEUR | 2017-10-08 | 2026-10-31 | 3311 |
+| FILEUR | 2020-10-15 | 2026-10-31 | 2208 |
+| FTTEUR | 2019-12-20 | 2022-11-15 | 1062 |
+| GMTEUR | 2022-03-09 | 2026-10-31 | 1698 |
+| ICXEUR | 2018-06-13 | 2026-09-03 | 3005 |
+| IOTAEUR | 2018-05-31 | 2026-10-31 | 3076 |
+| LINKEUR | 2019-01-16 | 2026-10-31 | 2846 |
+| LTCEUR | 2017-12-13 | 2026-10-31 | 3245 |
+| LUNAEUR | 2020-08-21 | 2022-05-13 | 631 |
+| MATICEUR | 2019-04-26 | 2024-09-10 | 1965 |
+| NEAREUR | 2020-10-14 | 2026-10-31 | 2209 |
+| NEOEUR | 2017-11-20 | 2026-10-31 | 3268 |
+| ONTEUR | 2018-06-08 | 2026-10-31 | 3068 |
+| OPEUR | 2022-06-01 | 2026-10-31 | 1614 |
+| ORDIEUR | 2023-11-07 | 2026-10-31 | 1090 |
+| PEPEEUR | 2023-05-05 | 2026-10-31 | 1276 |
+| POLEUR | 2024-09-13 | 2026-10-31 | 779 |
+| QTUMEUR | 2018-03-19 | 2026-10-31 | 3149 |
+| SANDEUR | 2020-08-14 | 2026-10-31 | 2270 |
+| SHIBEUR | 2021-05-10 | 2026-10-31 | 2001 |
+| SOLEUR | 2020-08-11 | 2026-10-31 | 2273 |
+| SUIEUR | 2023-05-03 | 2026-10-31 | 1278 |
+| TONEUR | 2024-08-08 | 2026-06-30 | 692 |
+| TRUMPEUR | 2025-01-19 | 2026-10-31 | 651 |
+| TRXEUR | 2018-06-11 | 2026-10-31 | 3065 |
+| UNIEUR | 2020-09-17 | 2026-10-31 | 2236 |
+| VETEUR | 2018-07-25 | 2026-10-31 | 3021 |
+| WIFEUR | 2024-03-05 | 2026-10-31 | 971 |
+| XLMEUR | 2018-05-31 | 2026-10-31 | 3076 |
+| XMREUR | 2019-03-15 | 2024-02-20 | 1804 |
+| XRPEUR | 2018-05-04 | 2026-10-31 | 3103 |
+| ZECEUR | 2019-03-21 | 2026-10-31 | 2782 |
+
+## BTC, ETH e SOL
+
+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=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 | 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 | 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 | 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 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 | 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` | 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 |
+|---|---:|
+| `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**
+
+| Coppia | Prima barra | Ultima barra | Barre |
+|---|---|---|---:|
+| BTCEUR | 2017-10-08 | 2026-10-31 | 3311 |
+| ETHEUR | 2017-10-08 | 2026-10-31 | 3311 |
+| SOLEUR | 2020-08-11 | 2026-10-31 | 2273 |
+
+## Cosa il backtest non rappresenta
+
+- I correttivi senza una storia ricostruibile (notizie, calendario economico, trimestrali, modello) non ricevono dati e non intervengono.
+- Le decisioni si prendono sulla chiusura e si eseguono all'apertura della seduta dopo, con lo scostamento stimato: nessun inseguimento con ordini limite.
+- Sharpe e volatilità sono calcolati senza tasso privo di rischio.
+- Limiti di rischio e regime crypto applicati come dal vivo. La strategia è il 40% del bot: il resto conta come liquidità ferma. Ogni chiusura vale come un giorno; se scatta l'interruttore, supponiamo che tu riparta dopo sette giorni. Età dei prezzi, prezzo dell'ordine e orologio esistono solo dal vivo.
+- Prezzi dello storico Binance in USDT convertiti in euro con il cambio BCE del giorno, contando un USDT come un dollaro: è un'approssimazione delle coppie in euro di OKX. Su questo storico lo spread non si può misurare: l'universo sono le monete con più scambi, passo di prezzo e quantità minima sono stime, i costi sono quelli di OKX.
diff --git a/docs/backtests/crypto_trend.outcome.json b/docs/backtests/crypto_trend.outcome.json
new file mode 100644
index 0000000..cdc0439
--- /dev/null
+++ b/docs/backtests/crypto_trend.outcome.json
@@ -0,0 +1,377 @@
+{
+ "passed": false,
+ "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": "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.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.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.0583,
+ -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.0651,
+ -0.0674,
+ -0.0681,
+ -0.0683,
+ -0.0678,
+ -0.0684,
+ -0.0691,
+ -0.0705,
+ -0.0724,
+ -0.0733,
+ -0.0725,
+ -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.0774,
+ -0.0781,
+ -0.0782,
+ -0.0776,
+ -0.0791,
+ -0.0786,
+ -0.0785,
+ -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.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.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.0992,
+ -0.0988,
+ -0.0996,
+ -0.1003,
+ -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.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.1116,
+ -0.1132,
+ -0.1133,
+ -0.1131,
+ -0.1132,
+ -0.114,
+ -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.1194,
+ -0.1184,
+ -0.1195,
+ -0.119,
+ -0.1195,
+ -0.1201,
+ -0.121,
+ -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.1277,
+ -0.1286,
+ -0.1292,
+ -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.1311,
+ -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.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
+ ]
+}
diff --git a/docs/backtests/equity_meanrev.md b/docs/backtests/equity_meanrev.md
new file mode 100644
index 0000000..0e96292
--- /dev/null
+++ b/docs/backtests/equity_meanrev.md
@@ -0,0 +1,10 @@
+# Backtest di `equity_meanrev` (Ritorno alla media azioni)
+
+**Esito: in attesa.** In attesa delle chiavi Alpaca: senza lo storico delle azioni il backtest non si può fare, quindi la strategia resta in osservazione.
+
+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 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.
+
diff --git a/docs/backtests/equity_meanrev.outcome.json b/docs/backtests/equity_meanrev.outcome.json
new file mode 100644
index 0000000..dce192e
--- /dev/null
+++ b/docs/backtests/equity_meanrev.outcome.json
@@ -0,0 +1,9 @@
+{
+ "passed": false,
+ "verdict": "In attesa delle chiavi Alpaca: senza lo storico delle azioni il backtest non si pu\u00F2 fare, quindi la strategia resta in osservazione.",
+ "report": "docs/backtests/equity_meanrev.md",
+ "max_drawdown": 0,
+ "expected_slippage_bp": 0,
+ "round_trip_cost": 0,
+ "expected_path_p5": []
+}
diff --git a/docs/backtests/equity_momentum.md b/docs/backtests/equity_momentum.md
new file mode 100644
index 0000000..bb5b331
--- /dev/null
+++ b/docs/backtests/equity_momentum.md
@@ -0,0 +1,10 @@
+# Backtest di `equity_momentum` (Momentum azioni)
+
+**Esito: in attesa.** In attesa delle chiavi Alpaca: senza lo storico delle azioni il backtest non si può fare, quindi la strategia resta in osservazione.
+
+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 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.
+
diff --git a/docs/backtests/equity_momentum.outcome.json b/docs/backtests/equity_momentum.outcome.json
new file mode 100644
index 0000000..87af21a
--- /dev/null
+++ b/docs/backtests/equity_momentum.outcome.json
@@ -0,0 +1,9 @@
+{
+ "passed": false,
+ "verdict": "In attesa delle chiavi Alpaca: senza lo storico delle azioni il backtest non si pu\u00F2 fare, quindi la strategia resta in osservazione.",
+ "report": "docs/backtests/equity_momentum.md",
+ "max_drawdown": 0,
+ "expected_slippage_bp": 0,
+ "round_trip_cost": 0,
+ "expected_path_p5": []
+}
diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs
index 56e6b63..ef1eec2 100644
--- a/src/Anubis.Server/AnubisHost.cs
+++ b/src/Anubis.Server/AnubisHost.cs
@@ -292,8 +292,23 @@ internal sealed partial class AnubisHost(
: null;
_trading = TradingEnabled && (identity.File ?? Installation.ReadFile(Config.Data)) is { } file
? new TradingService(_db, clock, bus, secrets, _market, new FxStore(_db, clock), TradingConsent.From(Config), file.InstallationId,
- overrides?.MarketHttp, overrides?.MarketSockets, logger)
+ overrides?.MarketHttp, overrides?.MarketSockets, logger, settings, (password, code, ct) => access.ReauthenticateAsync(password, code, ct),
+ Path.Combine(Config.Data.Root, "STOP"))
: null;
+ if (_trading is not null)
+ {
+ // Before "ready": the Strategie page must never show a strategy without its backtest outcome (SPEC 12.3).
+ // A failure here is logged and left to the trading start, which repeats it: the interface still opens.
+ try
+ {
+ await _trading.PrepareAsync(cancellationToken).ConfigureAwait(false);
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ LogTradingFailed(logger, ex);
+ }
+ }
+
// The laboratory computes on its own thread and reads only local data; the demo shows appendix F and runs none.
_lab = options.Demo ? null : new Laboratory(_db, clock, Config.Data.Research, logger);
_services = new AppServices(_db, settings, secrets, access, backups, scheduler, _market, _trading, _lab);
diff --git a/src/Anubis.Server/Assets/app.css b/src/Anubis.Server/Assets/app.css
index 2e81dd9..d9ca913 100644
--- a/src/Anubis.Server/Assets/app.css
+++ b/src/Anubis.Server/Assets/app.css
@@ -224,6 +224,7 @@ textarea {
.panel > h2 { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; }
.panel > h3, .panel h3 { margin: 20px 0 8px; }
.note { color: var(--text-3); font-size: 13px; line-height: 18px; }
+h2 .note, h3 .note { font-weight: 400; letter-spacing: 0; }
.hint { color: var(--text-3); font-size: 13px; line-height: 18px; }
.empty { display: flex; flex-direction: column; gap: 8px; color: var(--text-2); max-width: 70ch; }
.empty-title { color: var(--text); font-weight: 600; font-size: 15px; }
@@ -389,6 +390,138 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
.currency-lines dd { margin: 0; text-align: right; }
.fx-warning { margin-top: 16px; }
+/* ---- Operazioni ---- */
+.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
+.trades-head .lead { margin-top: 0; }
+.trades-head .big-number { margin-top: 8px; }
+.trades-head .note { margin-top: 10px; }
+.trades-head h2 { display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; }
+.cells { margin-bottom: 0; }
+.cells > div { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
+.cells dt { color: var(--text-3); font-size: 13px; }
+.cells dd { margin: 0; display: flex; flex-direction: column; gap: 2px; }
+.cells dd strong { font-size: 18px; line-height: 24px; font-weight: 650; letter-spacing: -0.015em; font-variant-numeric: tabular-nums; }
+.cells dd span { color: var(--text-3); font-size: 13px; }
+.result-bars { display: block; width: 100%; height: 170px; margin-top: 16px; }
+.result-bars .axis { stroke: var(--rule); stroke-width: 1; vector-effect: non-scaling-stroke; }
+.result-bars rect.gain { fill: var(--gain); }
+.result-bars rect.loss { fill: var(--loss); }
+.bars-scale { display: flex; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
+.filters { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 16px; }
+.filters .btn:last-child { margin-left: auto; }
+.search { position: relative; flex: 1 1 240px; display: flex; align-items: center; }
+.search .icon { position: absolute; left: 14px; color: var(--text-3); pointer-events: none; }
+.search input { width: 100%; padding-left: 40px !important; }
+.trades { display: flex; flex-direction: column; margin: 0 -22px; }
+.trade-row {
+ display: grid; grid-template-columns: 116px minmax(0, 1fr) 128px 70px 176px 146px minmax(0, 1.7fr) 20px;
+ gap: 12px; align-items: center; padding: 14px 22px; border-bottom: 1px solid var(--rule-inner); font-variant-numeric: tabular-nums;
+}
+.trade-header { color: var(--text-3); font-size: 13px; padding-top: 4px; padding-bottom: 8px; border-bottom: 1px solid var(--rule); }
+.trade-header::after { content: ""; }
+.trade-row .num { text-align: right; }
+.trade summary { list-style: none; cursor: pointer; }
+.trade summary::-webkit-details-marker { display: none; }
+.trade summary::after {
+ content: ""; justify-self: end; width: 8px; height: 8px; margin-right: 4px;
+ border-right: 2px solid var(--text-2); border-bottom: 2px solid var(--text-2); transform: rotate(45deg) translateY(-3px);
+}
+.trade[open] summary::after { transform: rotate(-135deg) translateY(-3px); }
+.trade summary:hover { background: var(--surface-2); }
+.trade[open] { background: var(--surface-2); }
+.trade[open] summary { border-bottom: 0; }
+.why { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px; padding: 4px 22px 22px; border-bottom: 1px solid var(--rule-inner); }
+.why-card { background: var(--surface); border: 1px solid var(--rule); border-radius: 12px; padding: 18px 20px; display: flex; flex-direction: column; gap: 10px; }
+.why-card h3 { margin: 0 !important; }
+.why-card .account-lines { margin-top: 4px; }
+.checks { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }
+.checks li { display: flex; align-items: flex-start; gap: 10px; }
+.checks .icon { margin-top: 2px; }
+.checks .ok .icon { color: var(--gain); }
+.checks .warn { color: var(--attention); }
+.checks .wait .icon { color: var(--text-2); }
+.pager { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; padding-top: 18px; }
+.pager .note { margin-right: auto; }
+
+/* ---- Strategie ---- */
+.stages { list-style: none; margin: 0; padding: 0; display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; }
+.stages li { border: 1px solid var(--rule); border-radius: 12px; padding: 16px 18px; display: flex; flex-direction: column; gap: 6px; }
+.stages li > strong { font-size: 15px; }
+.stages li > p { color: var(--text-2); font-size: 13.5px; }
+.stages li.here { border: 2px solid var(--text); background: var(--surface-2); padding: 15px 17px; }
+.stages .step { border: 1.5px solid var(--text); background: transparent; width: 24px; height: 24px; font-size: 13px; font-weight: 650; }
+.stages .here .step { background: var(--text); color: var(--surface); }
+.stage-count { display: flex; align-items: center; gap: 4px; margin-top: auto; padding-top: 6px; color: var(--text) !important; }
+.stage-count .swatch { margin-right: 0; }
+.stage-count strong { margin-left: 4px; }
+.strategy { display: grid; grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr) minmax(0, 1.15fr); padding: 0; }
+.strategy > div { padding: 24px 26px; min-width: 0; display: flex; flex-direction: column; gap: 12px; }
+.strategy > div + div { border-left: 1px solid var(--rule); }
+.strategy-about h2 { display: flex; align-items: center; gap: 4px; flex-wrap: wrap; font-size: 20px; line-height: 28px; }
+.strategy-about h2 .tag { margin-left: 10px; background: var(--info-bg); color: var(--link); }
+.strategy-about > p:first-of-type { font-size: 15px; line-height: 22px; }
+.strategy-about ul { margin: 0; padding-left: 20px; color: var(--text-2); display: flex; flex-direction: column; gap: 4px; }
+.strategy-about .note { margin-top: auto; }
+.strategy-number { display: flex; align-items: center; gap: 14px; font-size: 30px; line-height: 36px; font-weight: 650; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; }
+.spark { display: block; width: 100%; height: 80px; }
+.strategy-result .account-lines { grid-template-columns: max-content minmax(0, 1fr); column-gap: 16px; }
+.strategy-result .account-lines dd { overflow-wrap: anywhere; }
+.spark polyline { fill: none; stroke-width: 2; stroke-linejoin: round; }
+.strategy-steps h3 { margin: 0 !important; }
+.strategy-steps form { margin: 0; }
+.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; }
+.form-grid .btn { justify-self: start; }
+.confirm-live .form-grid { grid-template-columns: 1fr; }
+.plain { border-top: 2px solid var(--text); padding-top: 18px; }
+.plain > h2 { margin-bottom: 8px; }
+.observing { display: grid; grid-template-columns: minmax(180px, max-content) minmax(0, 1fr); margin: 0; }
+.observing dt, .observing dd { margin: 0; padding: 14px 0; border-bottom: 1px solid var(--rule-inner); }
+.observing dt { font-weight: 650; padding-right: 32px; }
+.observing dd { display: flex; align-items: center; justify-content: space-between; gap: 16px; color: var(--text-2); }
+.observing form { margin: 0; flex: none; }
+.attention { display: inline-flex; align-items: center; gap: 6px; }
+
+/* ---- Rischio ---- */
+.risk-top { display: grid; grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr); gap: 20px; align-items: stretch; }
+.risk-top .panel { display: flex; flex-direction: column; gap: 12px; }
+.risk-top .panel-head { margin-bottom: 0; }
+.risk-top p { color: var(--text-2); }
+.btn-danger-solid { background: var(--loss); border-color: var(--loss); color: var(--surface); }
+.btn-danger-solid:hover { background: var(--loss); opacity: .9; }
+.status-line.gain { display: flex; align-items: center; gap: 8px; color: var(--gain); font-weight: 600; font-size: 14px; white-space: normal; }
+.blocks { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
+.blocks li { display: flex; align-items: flex-start; gap: 10px; }
+.blocks .icon { margin-top: 2px; }
+.block-list { margin: 0; display: flex; flex-direction: column; }
+.block-list dt { color: var(--text-3); font-size: 13px; padding-top: 12px; border-top: 1px solid var(--rule-inner); }
+.block-list dd { margin: 0 0 12px; display: flex; flex-direction: column; gap: 2px; }
+.block-list dd span { color: var(--text-2); font-size: 13.5px; }
+.limits td.wide { width: 24%; vertical-align: middle; }
+.usage { display: block; position: relative; height: 6px; border-radius: 3px; background: var(--track); overflow: hidden; }
+.usage span { display: block; height: 100%; border-radius: 3px; background: var(--text-2); min-width: 2px; }
+.usage.high span { background: var(--attention); }
+.drawdown { display: block; width: 100%; height: auto; margin-top: 12px; overflow: visible; }
+.drawdown .axis { stroke: var(--rule); stroke-width: 1; }
+.drawdown .tick { fill: var(--text-3); font-size: 12px; }
+.drawdown .area { fill: var(--loss); opacity: .1; }
+.drawdown .line { fill: none; stroke: var(--loss); stroke-width: 2; stroke-linejoin: round; }
+.drawdown .dot { fill: var(--loss); }
+.drawdown .label { fill: var(--text); font-size: 12.5px; font-weight: 650; }
+.columns .panel .notice { margin-top: 12px; }
+.never { list-style: none; margin: 0; padding: 0; }
+.never li { display: flex; align-items: center; gap: 12px; padding: 12px 0; border-bottom: 1px solid var(--rule-inner); }
+.never .icon { color: var(--text-2); }
+.events { display: grid; grid-template-columns: 140px minmax(0, 1fr); margin: 0 0 12px; }
+.events dt, .events dd { margin: 0; padding: 12px 0; border-bottom: 1px solid var(--rule-inner); }
+.events dt { color: var(--text-3); }
+.limits-form { max-width: none; margin-bottom: 8px; }
+
/* ---- Service pages ---- */
.service { min-height: 100vh; display: flex; justify-content: center; padding: 48px 16px; }
.service-box { width: 100%; max-width: 720px; display: flex; flex-direction: column; gap: 16px; }
@@ -438,6 +571,25 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
.panel-tools { width: 100%; justify-content: space-between; }
.facts { grid-template-columns: 1fr; gap: 2px; }
.facts dd { margin-bottom: 8px; }
+ .panel > h2 { flex-direction: column; align-items: flex-start; gap: 4px; }
+ .trades-head .cells { grid-template-columns: 1fr 1fr; }
+ .trades { margin: 0 -18px; }
+ .trade-row { grid-template-columns: minmax(0, 1fr) auto 16px; gap: 4px 12px; padding: 12px 18px; }
+ .trade-row > span:first-child { grid-column: 1 / -1; color: var(--text-3); font-size: 13px; }
+ .trade-row .wide, .trade-header, .limits .wide, .filters .btn:last-child { display: none; }
+ .why { grid-template-columns: 1fr; padding: 4px 18px 18px; }
+ .filters > label:not(.search) { flex: 1 1 140px; }
+ .filters select { width: 100%; }
+ .stages { grid-template-columns: 1fr 1fr; gap: 10px; }
+ .strategy { grid-template-columns: 1fr; }
+ .strategy > div { padding: 18px; }
+ .strategy > div + div { border-left: 0; border-top: 1px solid var(--rule); }
+ .risk-top { grid-template-columns: 1fr; gap: 14px; }
+ .observing { grid-template-columns: 1fr; }
+ .observing dt { border-bottom: 0; padding-bottom: 0; }
+ .observing dd { flex-direction: column; align-items: flex-start; }
+ .events { grid-template-columns: 1fr; }
+ .events dt { border-bottom: 0; padding-bottom: 0; }
.bottombar {
display: grid; grid-template-columns: repeat(5, 1fr); gap: 4px; position: fixed; left: 0; right: 0; bottom: 0;
padding: 6px 6px calc(6px + env(safe-area-inset-bottom)); background: var(--surface); border-top: 1px solid var(--rule); z-index: 10;
diff --git a/src/Anubis.Server/BacktestCommand.cs b/src/Anubis.Server/BacktestCommand.cs
new file mode 100644
index 0000000..49096cc
--- /dev/null
+++ b/src/Anubis.Server/BacktestCommand.cs
@@ -0,0 +1,142 @@
+using System.Collections;
+using System.Globalization;
+using Anubis.Backtest;
+using Anubis.Brokers;
+using Anubis.Core;
+using Anubis.Data;
+using Anubis.Strategies;
+using Anubis.Trading;
+
+namespace Anubis.Server;
+
+///
I limiti valgono per tutte le strategie insieme. Abbassarli è sempre possibile. @(_anyLive ? "Una strategia usa soldi veri: per alzarne uno servono la frase e la password." : "Finché nessuna strategia usa soldi veri, puoi anche alzarli.")
+ @if (!Shell.IsDemo) + { + +Per ogni euro perso ne ha guadagnati
+@(v.PerEuroLost is { } per ? Shell.Money(per, c) : "—")
+Guadagni incassati finora: @Shell.Money(v.Net, c, withSign: true)@(f.Period == "avvio" && f.Strategy is null && f.Account is null ? "" : " con i filtri scelti")
+La migliore @Shell.Money(best.Eur, c, withSign: true) su @best.Symbol, la peggiore @Shell.Money(worst.Eur, c, withSign: true) su @worst.Symbol.
+ } + else + { +Nessuna operazione con questi filtri.
+ } +Nessuna operazione con questi filtri.
+ } + else + { +Per questa operazione non c'è la traccia della decisione d'acquisto: è precedente al registro delle decisioni o è stata aperta senza strategia.
+ } + else + { +@t.ExitReason.
+ } + else + { +"Ferma tutto", in alto, blocca il bot. Dopo averlo usato il bot si riattiva solo da qui, mai da solo e mai da Telegram.
- } +@{ + var v = _view; + var c = _currency; +} +@if (_message is { } message) +{ +C'è il file STOP nella cartella dei dati: toglilo, poi conferma qui la ripartenza.
Con Ferma tutto 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.
+ @if (!Shell.IsDemo) + { +Anche un file chiamato STOP nella cartella dei dati ferma tutto entro un minuto.
| Limite | Adesso | Quanto ne sto usando | Soglia | Se lo supero |
|---|---|---|---|---|
| @row.Label | +@row.Now@if (row.Detail is { } d) { |
+ + @if (row.Usage is { } u) + { + + } + | +@row.Threshold | +@row.Beyond | +
Ogni fotografia del patrimonio@(v.Risk.State.PeakFrom is { } from ? " dal " + Local(from, "d MMMM") : " dall'avvio"). A zero vuol dire che il portafoglio era al suo punto più alto.
+ @if (v.Drawdown.Count < 2) + { +Ancora troppo poche fotografie per disegnare la curva.
+ } + else + { + var worst = v.Drawdown.MinBy(p => p.Drawdown)!; + var floor = Math.Min(-0.01m, worst.Drawdown * 1.2m); + var first = v.Drawdown[0].At; + var span = Math.Max(1d, (v.Drawdown[^1].At - first).TotalSeconds); + string X(DateTimeOffset at) => Css((decimal)((at - first).TotalSeconds / span) * 560m + 30m); + string Y(decimal d) => Css(10m + d / floor * 150m); + var points = string.Join(' ', v.Drawdown.Select(p => X(p.At) + "," + Y(p.Drawdown))); + +
+ @if (-worst.Drawdown < v.Limits.DrawdownHalf / 5m)
+ {
+
Quanto perderei con le posizioni di adesso. Gli scenari si cambiano in Impostazioni.
+ @if (!v.HasPositions) + { +Nessuna posizione aperta: oggi nessuno scenario costerebbe nulla.
+ } + else + { +| Scenario | Senza stop | Con gli stop |
|---|---|---|
| @s.Scenario.Label | +@Shell.Money(s.WithoutStops, c, decimals: 0) (@Format.Percent(s.WithoutStopsShare * 100m, 1, withSign: true)) | +@(s.SameWithStops ? "uguale" : "circa " + Shell.Money(s.WithStops ?? 0m, c, decimals: 0)) | +
@StageText(stage)
++ @if (here.Count == 0) + { + Nessuna strategia + } + else + { + @foreach (var x in here) + { + + } + @(here.Count == 1 ? "1 strategia" : $"{here.Count} strategie") + } +
+@s.Description
+Conto @s.Account. Capitale assegnato: @Shell.Money(s.CapitalEur, c, decimals: 0).
+@Shell.Money(s.ResultEur, c, withSign: true)
@(s.DaysToGo is { } d ? $"Disponibile tra {d} {(d == 1 ? "giorno" : "giorni")}, se gli altri requisiti reggono" : "Non ancora: mancano dei requisiti")
+ @if (s.Requirements.Any(r => !r.Met && !StrategiesView.IsPending(r))) + { +@(v.LiveAllowed ? "Serve un conto reale di " + (broker == "okx" ? "OKX" : "Alpaca") + " nelle Impostazioni." : "La configurazione d'avvio non consente i soldi veri.")
+ } + else + { +Nessuna strategia di base in osservazione.
+ } + else + { +@report}
+ @if (passed && !Shell.IsDemo)
+ {
+
+ }
+ else if (!passed)
+ {
+ (null)); + var limits = await RiskSettings.LoadAsync(services.Settings, cancellationToken).ConfigureAwait(false); + 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(); + 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; + + var (index, sent) = await services.Db.ReadAsync(async s => + { + var i = await s.QueryAsync("SELECT taken_at, twr_index FROM equity_snapshots WHERE scope = 'total' AND world = @w AND twr_index IS NOT NULL ORDER BY taken_at, id", + r => new IndexPoint(r.Moment("taken_at"), r.Money("twr_index")), ("w", world)).ConfigureAwait(false); + var o = await s.QueryAsync( + "SELECT o.account_id, COUNT(*) AS n FROM orders o WHERE o.submitted_at >= @f AND o.purpose IN ('entry', 'exit') GROUP BY o.account_id", + r => (Account: r.Id("account_id"), Count: r.Number("n")), ("f", now - TimeSpan.FromMinutes(1))).ConfigureAwait(false); + return (i, o); + }, cancellationToken).ConfigureAwait(false); + + var shown = accounts.Accounts.Select(a => a.Id).ToHashSet(); + var equity = accounts.TotalEur; + var positions = accounts.Positions; + var biggest = positions.MaxBy(p => p.ValueEur); + var crypto = positions.Where(p => p.Broker == Venues.Okx).Sum(p => p.ValueEur); + decimal Rate(PositionRow p) => p.Last == 0m ? 0m : p.ValueEur / (p.Quantity * p.Last); + var atRisk = positions.Select(p => p.Stop is { } stop ? Math.Max(0m, p.ValueEur - (p.Quantity * stop * Rate(p))) : p.ValueEur).ToList(); + var perMinute = sent.Where(x => shown.Contains(x.Account)).Select(x => x.Count).DefaultIfEmpty(0).Max(); + + string Pct(decimal fraction, int decimals = 2, bool sign = false) => Format.Percent(fraction * 100m, decimals, sign); + decimal? Use(decimal value, decimal limit) => limit <= 0m ? null : Math.Clamp(value / limit, 0m, 1m); + var m = risk.Measures; + var rows = new List + { + new("Perdita in un giorno", m.DayChange >= 0m ? "nessuna" : Pct(m.DayChange), m.DayChange >= 0m ? $"oggi {Pct(m.DayChange, 2, true)}" : null, + Use(-m.DayChange, limits.DailyLoss), Pct(-limits.DailyLoss), "Niente nuovi ingressi per 24 ore", RiskSettings.DailyLoss.Key), + new("Perdita in una settimana", m.WeekChange >= 0m ? "nessuna" : Pct(m.WeekChange), m.WeekChange >= 0m ? $"{Pct(m.WeekChange, 2, true)}" : null, + Use(-m.WeekChange, limits.WeeklyLoss), Pct(-limits.WeeklyLoss), "Rischio dimezzato per sette giorni", RiskSettings.WeeklyLoss.Key), + new("Calo dal massimo", Pct(m.Drawdown), Worst(index, risk.State.PeakFrom) is { } worst && worst < m.Drawdown ? $"peggiore {Pct(worst)}" : null, + Use(-m.Drawdown, limits.DrawdownStop), $"{Pct(-limits.DrawdownHalf, 0)} e {Pct(-limits.DrawdownStop, 0)}", + $"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 || 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", 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 || 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), + new("Età dei prezzi", "controllata a ogni ordine", null, null, $"{(int)limits.MaxPriceAge.TotalSeconds} secondi", "Non apro posizioni finché i dati non tornano freschi", + RiskSettings.MaxPriceAge.Key), + }; + + var drawdown = new List (); + var peak = 0m; + foreach (var p in index.Where(p => risk.State.PeakFrom is null || p.At >= risk.State.PeakFrom)) + { + peak = Math.Max(peak, p.Index); + drawdown.Add(new DrawdownPoint(p.At, peak > 0m ? (p.Index / peak) - 1m : 0m)); + } + + var scenarioText = (await services.Settings.GetAsync(Anubis.Risk.Scenarios.Setting.Key, cancellationToken).ConfigureAwait(false)).Value; + var dollars = accounts.Accounts.Where(a => a.Currency == "USD").Sum(a => a.Eur(a.Equity)); + var scenarios = Anubis.Risk.Scenarios.Compute(Anubis.Risk.Scenarios.Parse(scenarioText), + [.. positions.Select(p => new ScenarioPosition(p.Broker == Venues.Okx, p.ValueEur, p.Stop is { } stop ? p.Quantity * stop * Rate(p) : null))], dollars, equity); + + var calendar = await new CalendarEventStore(services.Db, clock).BetweenAsync(now.AddDays(-14), now.AddDays(14), cancellationToken).ConfigureAwait(false); + var windows = calendar.Select(e => (Event: e, Window: CalendarBlocks.Window(e))).Where(x => x.Window is not null) + .Select(x => (x.Window!.Value.From, x.Window.Value.To, x.Event.Title)).OrderBy(x => x.From).ToList(); + (DateTimeOffset, DateTimeOffset, string)? next = windows.FirstOrDefault(w => w.To > now) is { Title: not null } n ? n : null; + (DateTimeOffset, DateTimeOffset, string)? last = windows.LastOrDefault(w => w.To <= now) is { Title: not null } l ? l : null; + + 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, tripped); + } + + private static decimal? Worst(IReadOnlyList index, DateTimeOffset? from) + { + decimal? worst = null; + var peak = 0m; + foreach (var p in index.Where(p => from is null || p.At >= from)) + { + peak = Math.Max(peak, p.Index); + var d = peak > 0m ? (p.Index / peak) - 1m : 0m; + worst = worst is null ? d : Math.Min(worst.Value, d); + } + + return worst; + } +} diff --git a/src/Anubis.Server/StrategiesView.cs b/src/Anubis.Server/StrategiesView.cs new file mode 100644 index 0000000..2dccabf --- /dev/null +++ b/src/Anubis.Server/StrategiesView.cs @@ -0,0 +1,210 @@ +using Anubis.Backtest; +using Anubis.Core; +using Anubis.Data; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Server; + +/// A strategy of the Strategie screen: its stage, results, requirements and what the user can do next. +internal sealed record StrategyCard( + StrategyStage Stage, + string Name, + string Description, + IReadOnlyListRules, + string Account, + string Currency, + decimal CapitalEur, + decimal ResultEur, + decimal ResultPercent, + decimal WorstFall, + int Closed, + int Winners, + IReadOnlyList Open, + IReadOnlyList<(DateTimeOffset At, decimal Index)> Curve, + IReadOnlyList Requirements, + string Phrase, + int? DaysToGo, + IReadOnlyList Summary, + decimal? TwinGap) +{ + public string Color => "var(--s-" + Stage.Strategy.Replace('_', '-') + ")"; + + public bool AllMet => Requirements.All(r => r.Met); +} + +/// +/// The Strategie screen (SPEC 12.3, 13.6, mockup 04): the path to real money in four stages, a card for each base +/// strategy with its requirements, and the ones in observation with the reason. +/// +internal sealed record StrategiesView(IReadOnlyListCards, bool LiveAllowed, IReadOnlyList<(Guid Id, string Name, string Broker)> LiveAccounts) +{ + /// What each base strategy does, in four lines (SPEC 8). + public static readonly IReadOnlyDictionary> Rules = new Dictionary >(StringComparer.Ordinal) + { + [StrategyNames.CryptoTrend] = + [ + "Guarda le 10 monete in euro più scambiate una volta al giorno, dopo la chiusura delle 00:00 UTC", + "Entra quando il prezzo segna nuovi massimi su più periodi, da 5 a 360 giorni", + "Più una moneta è agitata, meno ne compra", + "Mai a leva, mai al ribasso", + ], + [StrategyNames.EquityMomentum] = + [ + "Rifà la classifica ogni lunedì e tiene fino a 12 titoli", + "Vende chi esce dai primi 30 o tocca lo stop", + "Compra solo quando il mercato nel suo insieme sale", + "Solo azioni singole, nessun ETF americano", + ], + [StrategyNames.EquityMeanrev] = + [ + "Solo titoli sopra la loro media a 200 giorni", + "Esce al rimbalzo, oppure dopo 5 sedute", + "Salta i giorni prima delle trimestrali", + "Mai uscita nello stesso giorno dell'acquisto", + ], + }; + + public static async Task LoadAsync(AppServices services, IClock clock, bool liveAllowed, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(services); + var stages = services.Trading?.Stages ?? new StageBook(services.Db, clock, TradingConsent.None, (_, _, _) => Task.FromResult(false)); + var ledger = services.Trading?.Ledger ?? new Ledger(services.Db, clock); + var rate = (await new FxStore(services.Db, clock).LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false))?.Rate ?? 0m; + var accounts = await services.Db.ReadAsync(s => s.QueryAsync("SELECT id, name, broker, environment, base_currency FROM accounts", + r => (Id: r.Id("id"), Name: r.Text("name"), Broker: r.Text("broker"), Environment: r.Text("environment"), Currency: r.Text("base_currency"))), cancellationToken) + .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 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 (); + foreach (var stage in await stages.AllAsync(cancellationToken).ConfigureAwait(false)) + { + if (!StrategyNames.Base.Any(b => b.Name == stage.Strategy)) + { + continue; + } + + var family = StrategyCatalog.Find(stage.Strategy); + var ledgerAccount = stage.OrdersAccount ?? stage.AccountId; + var account = accounts.FirstOrDefault(a => a.Id == ledgerAccount); + var usd = account.Currency == "USD"; + decimal Eur(decimal amount) => usd ? (rate > 0m ? amount / rate : 0m) : amount; + var equity = equities.FirstOrDefault(e => e.AccountId == ledgerAccount && e.Strategy == stage.Strategy); + // As on Conti: each position is valued to the cent before the sum, so both pages show the same figure. + var held = positions.Where(p => p.AccountId == ledgerAccount && p.Strategy == stage.Strategy).Sum(p => Math.Round(p.Value, 2, MidpointRounding.AwayFromZero)); + var result = equity is null ? 0m : equity.Cash + held - equity.Flows; + var since = stage.StageSince ?? DateTimeOffset.MinValue; + var (curve, trades) = await services.Db.ReadAsync(async s => + { + var c = await s.QueryAsync( + "SELECT taken_at, twr_index FROM equity_snapshots WHERE scope = 'strategy' AND account_id = @a AND strategy = @s AND twr_index IS NOT NULL ORDER BY taken_at, id", + r => (At: r.Moment("taken_at"), Index: r.Money("twr_index")), ("a", ledgerAccount), ("s", stage.Strategy)).ConfigureAwait(false); + var t = await s.QueryAsync("SELECT realized FROM trades WHERE account_id = @a AND strategy = @s AND status = 'closed'", r => r.Money("realized"), + ("a", ledgerAccount), ("s", stage.Strategy)).ConfigureAwait(false); + return (c, t); + }, cancellationToken).ConfigureAwait(false); + var peak = 0m; + var worst = 0m; + foreach (var p in curve) + { + peak = Math.Max(peak, p.Index); + worst = Math.Min(worst, peak > 0m ? (p.Index / peak) - 1m : 0m); + } + + var symbols = new List (); + foreach (var p in positions.Where(p => p.AccountId == ledgerAccount && p.Strategy == stage.Strategy)) + { + 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 (); + 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 (); + 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); + var next = stage.Stage == StrategyStages.Reduced ? StrategyStages.Real : StrategyStages.Reduced; + var days = requirements.FirstOrDefault(r => r.Key == "days"); + int? toGo = days is { Met: false } && stage.StageSince is { } from + ? Math.Max(1, (int)Math.Ceiling(((stage.Stage == StrategyStages.Reduced ? StageBook.ReducedDays : StageBook.SimulationDays) - (clock.UtcNow - from).TotalDays))) + : null; + var flows = equity?.Flows ?? 0m; + 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, summary, twinGap)); + } + + var live = accounts.Where(a => a.Environment == TradingEnvironments.Live).Select(a => (a.Id, a.Name, a.Broker)).ToList(); + return new StrategiesView([.. cards.OrderBy(c => StrategyNames.Base.ToList().FindIndex(b => b.Name == c.Stage.Strategy))], liveAllowed, live); + } + + /// A requirement not met yet only because time has to pass or nothing could be measured so far. + public static bool IsPending(Requirement requirement) + { + ArgumentNullException.ThrowIfNull(requirement); + return !requirement.Met && (requirement.Key is "days" or "trades" || requirement.Value is "da misurare" or "nessuna esecuzione"); + } + + ///Why a strategy is in observation, in words: the outcome of its backtest, or the user's choice. + public static string ObservationReason(StrategyStage stage) + { + ArgumentNullException.ThrowIfNull(stage); + if (stage.Qualification is { Passed: false } q) + { + return q.Verdict; + } + + if (stage.Qualification is null) + { + return "Il backtest non è ancora stato fatto: finché manca resta in osservazione."; + } + + return stage.StageReason switch + { + "user" or null => "Superato il backtest: puoi portarla in simulazione quando vuoi.", + var r => "Tornata in osservazione: " + ReasonTexts.Text(r) + ".", + }; + } + + ///The report of a strategy's backtest in the repository, for the link. + public static string? ReportOf(StrategyStage stage) => stage.Qualification?.Report ?? BacktestOutcomes.Find(stage.Strategy)?.Report; +} diff --git a/src/Anubis.Server/TradesView.cs b/src/Anubis.Server/TradesView.cs new file mode 100644 index 0000000..2909280 --- /dev/null +++ b/src/Anubis.Server/TradesView.cs @@ -0,0 +1,198 @@ +using System.Globalization; +using System.Text; +using Anubis.Core; +using Anubis.Data; +using Anubis.Trading; + +namespace Anubis.Server; + +///The filters of the Operazioni screen, read from the address so a filtered page can be bookmarked. +internal sealed record TradeFilter(string? Search, Guid? Account, string? Strategy, string? Result, string Period, int Page) +{ + public const int PageSize = 20; + + public static readonly IReadOnlyList<(string Key, string Label)> Periods = [("avvio", "Dall'avvio"), ("7", "Ultimi 7 giorni"), ("30", "Ultimi 30 giorni"), ("90", "Ultimi 90 giorni")]; + + public static readonly IReadOnlyList<(string Key, string Label)> Results = [("", "Guadagni e perdite"), ("guadagni", "Solo guadagni"), ("perdite", "Solo perdite")]; + + public static TradeFilter Parse(string? search, string? account, string? strategy, string? result, string? period, string? page) => new( + string.IsNullOrWhiteSpace(search) ? null : search.Trim(), + Guid.TryParse(account, out var a) ? a : null, + string.IsNullOrWhiteSpace(strategy) ? null : strategy, + result is "guadagni" or "perdite" ? result : null, + Periods.Any(p => p.Key == period) ? period! : "avvio", + int.TryParse(page, NumberStyles.None, CultureInfo.InvariantCulture, out var p) && p > 0 ? p : 1); + + ///The query string of this filter with one value changed. + public string Query(int? page = null) + { + var parts = new List(); + void Add(string key, string? value) + { + if (!string.IsNullOrEmpty(value)) + { + parts.Add(key + "=" + Uri.EscapeDataString(value)); + } + } + + Add("cerca", Search); + Add("conto", Account?.ToString()); + Add("strategia", Strategy); + Add("esito", Result); + Add("periodo", Period == "avvio" ? null : Period); + var p = page ?? Page; + Add("pagina", p > 1 ? p.ToString(CultureInfo.InvariantCulture) : null); + return parts.Count == 0 ? "" : "?" + string.Join('&', parts); + } +} + +/// A step of the "why" card: a stage of a decision in plain Italian. +internal sealed record WhyLine(string Text, bool Good); + +///A closed trade of the Operazioni screen, in its own currency and in euro. +internal sealed record TradeRow(Guid Id, string Symbol, string Name, string Strategy, string Account, string Currency, DateTimeOffset OpenedAt, DateTimeOffset ClosedAt, + decimal Quantity, decimal EntryPrice, decimal ExitPrice, decimal Realized, decimal RealizedEur, decimal Fees, string ExitReason, string? ExitCode, + IReadOnlyListBought, IReadOnlyList Sold, decimal? EntrySlipBp, decimal? ExitSlipBp) +{ + public decimal Percent => EntryPrice * Quantity == 0m ? 0m : Realized / (EntryPrice * Quantity) * 100m; +} + +/// +/// The Operazioni screen (SPEC 13.6, mockup 03): closed trades with their figures, filters, the result of each +/// trade as bars, and for each one the "why" card built from the rows of the decisions table (SPEC 5.2). +/// +internal sealed record TradesView( + IReadOnlyListRows, + int Matching, + int Total, + DateTimeOffset? Since, + decimal Gains, + decimal Losses, + int Winners, + decimal Fees, + IReadOnlyList<(DateTimeOffset At, decimal Eur, string Symbol)> Bars, + IReadOnlyList<(Guid Id, string Name)> Accounts, + IReadOnlyList Strategies) +{ + public int Losers => Matching - Winners; + + /// Euro gained for each euro lost: null while nothing was lost. + public decimal? PerEuroLost => Losses < 0m ? Gains / -Losses : null; + + public decimal Net => Gains + Losses; + + public static async TaskLoadAsync(AppServices services, IClock clock, TradeFilter filter, int? limit, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(filter); + var rate = (await new FxStore(services.Db, clock).LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false))?.Rate ?? 0m; + var (accounts, trades) = await services.Db.ReadAsync(async s => + { + var a = await s.QueryAsync("SELECT id, name, environment, base_currency FROM accounts ORDER BY broker DESC, created_at", + r => (Id: r.Id("id"), Name: r.Text("name"), Environment: r.Text("environment"), Currency: r.Text("base_currency"))).ConfigureAwait(false); + var t = await s.QueryAsync( + "SELECT t.id, t.account_id, t.instrument_id, t.strategy, t.opened_at, t.closed_at, t.bought_quantity, t.bought_value, t.sold_quantity, t.sold_value, t.fees, t.realized, " + + "t.exit_reason, i.symbol, i.name FROM trades t JOIN instruments i ON i.id = t.instrument_id WHERE t.status = 'closed' ORDER BY t.closed_at DESC, t.id", + r => new Closed(r.Id("id"), r.Id("account_id"), r.Id("instrument_id"), r.Text("strategy"), r.Moment("opened_at"), r.Moment("closed_at"), r.Money("bought_quantity"), + r.Money("bought_value"), r.Money("sold_quantity"), r.Money("sold_value"), r.Money("fees"), r.Money("realized"), r.TextOrNull("exit_reason"), r.Text("symbol"), + r.TextOrNull("name") ?? "")).ConfigureAwait(false); + return (a, t); + }, cancellationToken).ConfigureAwait(false); + + // One world only, as on the Conti screen: real accounts when there are any, so finto and vero never add up. + var world = accounts.Any(a => TradingEnvironments.World(a.Environment) == Worlds.Real) ? Worlds.Real : Worlds.Simulated; + var shown = accounts.Where(a => TradingEnvironments.World(a.Environment) == world).ToDictionary(a => a.Id); + decimal Eur(Guid account, decimal amount) => shown[account].Currency == "USD" ? (rate > 0m ? amount / rate : 0m) : amount; + var all = trades.Where(t => shown.ContainsKey(t.Account)).ToList(); + var from = filter.Period switch + { + "7" => clock.UtcNow.AddDays(-7), + "30" => clock.UtcNow.AddDays(-30), + "90" => clock.UtcNow.AddDays(-90), + _ => (DateTimeOffset?)null, + }; + var matching = all.Where(t => + (filter.Account is null || t.Account == filter.Account) && + (filter.Strategy is null || t.Strategy == filter.Strategy) && + (from is null || t.ClosedAt >= from) && + (filter.Result is null || (filter.Result == "guadagni" ? t.Realized >= 0m : t.Realized < 0m)) && + (filter.Search is null || t.Symbol.Contains(filter.Search, StringComparison.OrdinalIgnoreCase) || t.Name.Contains(filter.Search, StringComparison.OrdinalIgnoreCase))) + .ToList(); + + var page = limit is { } n ? matching.Take(n).ToList() : matching.Skip((filter.Page - 1) * TradeFilter.PageSize).Take(TradeFilter.PageSize).ToList(); + var rows = new List (); + foreach (var t in page) + { + var (bought, sold, entrySlip, exitSlip, code) = await WhyAsync(services, t, cancellationToken).ConfigureAwait(false); + var quantity = t.BoughtQuantity; + rows.Add(new TradeRow(t.Id, t.Symbol, t.Name, t.Strategy, shown[t.Account].Name, shown[t.Account].Currency, t.OpenedAt, t.ClosedAt, quantity, + quantity == 0m ? 0m : t.BoughtValue / quantity, t.SoldQuantity == 0m ? 0m : t.SoldValue / t.SoldQuantity, t.Realized, + Math.Round(Eur(t.Account, t.Realized), 2, MidpointRounding.AwayFromZero), t.Fees, ReasonTexts.Exit(code ?? t.ExitReason), code ?? t.ExitReason, bought, sold, entrySlip, + exitSlip)); + } + + var bars = matching.OrderBy(t => t.ClosedAt).Select(t => (t.ClosedAt, Math.Round(Eur(t.Account, t.Realized), 2, MidpointRounding.AwayFromZero), t.Symbol)).ToList(); + return new TradesView(rows, matching.Count, all.Count, all.Count > 0 ? all.Min(t => t.ClosedAt) : null, + bars.Where(b => b.Item2 >= 0m).Sum(b => b.Item2), bars.Where(b => b.Item2 < 0m).Sum(b => b.Item2), bars.Count(b => b.Item2 >= 0m), + matching.Sum(t => Math.Round(Eur(t.Account, t.Fees), 2, MidpointRounding.AwayFromZero)), bars, + [.. shown.Values.Select(a => (a.Id, a.Name))], [.. all.Select(t => t.Strategy).Distinct().Order(StringComparer.Ordinal)]); + } + + /// The trades as CSV for an Italian spreadsheet: semicolons, decimal commas, one row per closed trade. + public string Csv() + { + var text = new StringBuilder("chiusa_il;aperta_il;strumento;nome;strategia;conto;quantita;prezzo_entrata;prezzo_uscita;valuta;risultato;risultato_eur;commissioni;motivo\n"); + foreach (var r in Rows) + { + text.Append(string.Join(';', Moment(r.ClosedAt), Moment(r.OpenedAt), Clean(r.Symbol), Clean(r.Name), r.Strategy, Clean(r.Account), Number(r.Quantity), Number(r.EntryPrice), + Number(r.ExitPrice), r.Currency, Number(r.Realized), Number(r.RealizedEur), Number(r.Fees), Clean(r.ExitReason))).Append('\n'); + } + + return text.ToString(); + + static string Moment(DateTimeOffset at) => at.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture); + + static string Number(decimal value) => (Math.Round(value, 8) / 1.000000000000000000000000000000000m).ToString(CultureInfo.InvariantCulture).Replace('.', ','); + + static string Clean(string value) => value.Replace(';', ',').Replace('\n', ' '); + } + + private sealed record Closed(Guid Id, Guid Account, Guid Instrument, string Strategy, DateTimeOffset OpenedAt, DateTimeOffset ClosedAt, decimal BoughtQuantity, decimal BoughtValue, + decimal SoldQuantity, decimal SoldValue, decimal Fees, decimal Realized, string? ExitReason, string Symbol, string Name); + + ///+ /// The decisions behind a trade: the first purchase and the last sale of its executions, matched to their decision + /// through the order key (the hash of the decision id), and every stage of those decisions in words. + /// + private static async Task<(ListBought, List Sold, decimal? EntrySlip, decimal? ExitSlip, string? ExitCode)> WhyAsync(AppServices services, Closed t, + CancellationToken cancellationToken) + { + var (executions, decisions) = await services.Db.ReadAsync(async s => + { + var e = await s.QueryAsync( + "SELECT side, order_key, reference_price, purpose, started_at FROM executions WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND started_at >= @f AND started_at <= @t " + + "ORDER BY started_at, id", + r => (Side: r.Text("side"), Key: r.Text("order_key"), Reference: r.MoneyOrNull("reference_price"), Purpose: r.Text("purpose")), + ("a", t.Account), ("i", t.Instrument), ("s", t.Strategy), ("f", t.OpenedAt.AddMinutes(-5)), ("t", t.ClosedAt)).ConfigureAwait(false); + var d = await s.QueryAsync( + "SELECT decision_id, stage, outcome, reasons, data FROM decisions WHERE strategy = @s AND symbol = @sym AND created_at >= @f AND created_at <= @t ORDER BY created_at, id", + r => (Id: r.Id("decision_id"), Stage: r.Text("stage"), Outcome: r.Text("outcome"), Reasons: r.Text("reasons"), Data: r.TextOrNull("data")), + ("s", t.Strategy), ("sym", t.Symbol), ("f", t.OpenedAt.AddDays(-1)), ("t", t.ClosedAt.AddMinutes(5))).ConfigureAwait(false); + return (e, d); + }, cancellationToken).ConfigureAwait(false); + + var byKey = decisions.GroupBy(d => d.Id).ToDictionary(g => ClientOrderIds.Key(g.Key), g => g.ToList(), StringComparer.Ordinal); + List Lines(string? key) => key is not null && byKey.TryGetValue(key, out var rows) + ? [.. rows.SelectMany(r => ReasonTexts.Stage(r.Stage, r.Outcome, System.Text.Json.JsonSerializer.Deserialize >(r.Reasons) ?? [], r.Data))] + : []; + var buy = executions.FirstOrDefault(e => e.Side == "buy"); + var sell = executions.LastOrDefault(e => e.Side == "sell"); + var sold = Lines(sell.Key); + var code = sell.Key is not null && byKey.TryGetValue(sell.Key, out var exitRows) + ? exitRows.Where(r => r.Stage == DecisionStages.Strategy).SelectMany(r => System.Text.Json.JsonSerializer.Deserialize
>(r.Reasons) ?? []).FirstOrDefault() + : sell.Purpose is "stop" or "protective" ? "stop" : null; + decimal? entrySlip = buy.Reference is > 0m && t.BoughtQuantity > 0m ? Math.Round(((t.BoughtValue / t.BoughtQuantity) / buy.Reference.Value - 1m) * 10_000m, 1) : null; + decimal? exitSlip = sell.Reference is > 0m && t.SoldQuantity > 0m ? Math.Round((1m - (t.SoldValue / t.SoldQuantity) / sell.Reference.Value) * 10_000m, 1) : null; + return (Lines(buy.Key), sold, entrySlip, exitSlip, code); + } +} diff --git a/src/Anubis/Access/AccessStore.cs b/src/Anubis/Access/AccessStore.cs index 6559b0f..19aaaa9 100644 --- a/src/Anubis/Access/AccessStore.cs +++ b/src/Anubis/Access/AccessStore.cs @@ -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; @@ -306,6 +310,34 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets, return true; } + ///
+ /// 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. After five wrong attempts in 15 minutes every attempt fails, + /// even with the right password, until the window has passed. + /// + public async TaskReauthenticateAsync(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)) + { + return false; + } + + 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; + } + /// Turning the second factor off asks for both: the password and a code from the app. public async TaskDisableSecondFactorAsync(Guid userId, string password, string? code, CancellationToken cancellationToken = default) { diff --git a/src/Anubis/Anubis.csproj b/src/Anubis/Anubis.csproj index 7cc3c05..7ee364e 100644 --- a/src/Anubis/Anubis.csproj +++ b/src/Anubis/Anubis.csproj @@ -10,6 +10,8 @@ + + diff --git a/src/Anubis/Backtest/Dataset.cs b/src/Anubis/Backtest/Dataset.cs index 1d2247e..5749727 100644 --- a/src/Anubis/Backtest/Dataset.cs +++ b/src/Anubis/Backtest/Dataset.cs @@ -102,14 +102,20 @@ public sealed class BacktestDataset { private readonly Dictionary _bySymbol; - public BacktestDataset(IEnumerable instruments, string currency) + /// Every instrument, the tradable ones and those used only as data. + /// The one currency of the backtest. + /// The market's sessions, which may go beyond the bars; null means the days with bars. + /// Instruments the strategy reads but never trades, such as SPY for the market filter. + public BacktestDataset(IEnumerable instruments, string currency, IEnumerable ? calendar = null, IEnumerable ? dataOnly = null) { ArgumentNullException.ThrowIfNull(instruments); Instruments = [.. instruments.OrderBy(i => i.Symbol, StringComparer.Ordinal)]; Currency = currency; _bySymbol = Instruments.ToDictionary(i => i.Symbol, StringComparer.Ordinal); Sessions = [.. Instruments.SelectMany(i => i.Bars.Select(b => b.Day)).Distinct().Order()]; - var wrong = Instruments.FirstOrDefault(i => i.Spec.QuoteCurrency != currency); + Calendar = [.. (calendar ?? []).Concat(Sessions).Distinct().Order()]; + DataOnly = new SortedSet (dataOnly ?? [], StringComparer.Ordinal); + var wrong = Instruments.FirstOrDefault(i => i.Spec.QuoteCurrency != currency && !DataOnly.Contains(i.Symbol)); if (wrong is not null) { throw new ArgumentException($"{wrong.Symbol} is in {wrong.Spec.QuoteCurrency}, the backtest is in {currency}", nameof(instruments)); @@ -118,11 +124,47 @@ public sealed class BacktestDataset public IReadOnlyList Instruments { get; } + /// The instruments the strategy may trade: every one but those used only as data. + public IEnumerableTradable => Instruments.Where(i => !DataOnly.Contains(i.Symbol)); + + public IReadOnlySet DataOnly { get; } + public string Currency { get; } public IReadOnlyList Sessions { get; } - public bool IsCrypto => Instruments.Count > 0 && Instruments.All(i => i.Spec.AssetClass == AssetClasses.Crypto); + /// + /// The market calendar: the sessions with bars and, when given, the later ones. Cutting the data keeps it whole, + /// because a calendar is known in advance. + /// + public IReadOnlyListCalendar { get; } + + /// The next session after + public DateOnly? NextSession(DateOnly day) + { + if (IsCrypto) + { + return day.AddDays(1); + } + + int lo = 0, hi = Calendar.Count; + while (lo < hi) + { + var mid = (lo + hi) / 2; + if (Calendar[mid] <= day) + { + lo = mid + 1; + } + else + { + hi = mid; + } + } + + return lo < Calendar.Count ? Calendar[lo] : null; + } + + public bool IsCrypto => Instruments.Count > 0 && Tradable.All(i => i.Spec.AssetClass == AssetClasses.Crypto); ///: every day for crypto, the calendar for stocks. Sessions in a year, to annualise: crypto trades every day, stocks about 252 days. public int PeriodsPerYear => IsCrypto ? 365 : 252; @@ -130,13 +172,15 @@ public sealed class BacktestDataset public BacktestInstrument? this[string symbol] => _bySymbol.GetValueOrDefault(symbol); ///The same data cut after - public BacktestDataset Through(DateOnly day) => new(Instruments.Select(i => i.Through(day)), Currency); + public BacktestDataset Through(DateOnly day) => new(Instruments.Select(i => i.Through(day)), Currency, Calendar, DataOnly); ///: what was known on that day (SPEC 12.2, step 2). The same data between two days, both included. public BacktestDataset Between(DateOnly from, DateOnly to) => new( Instruments.Select(i => new BacktestInstrument(i.Spec, [.. i.Bars.Where(b => b.Day >= from && b.Day <= to)], [.. i.Actions.Where(a => a.ExDate > from && a.ExDate <= to)], i.Source)) .Where(i => i.Bars.Count > 0), - Currency); + Currency, + Calendar.Where(d => d >= from), + DataOnly); ////// A SHA-256 of every bar, action and rule used: two reports with the same fingerprint and the same plan were @@ -146,10 +190,16 @@ public sealed class BacktestDataset { var text = new StringBuilder(); text.Append(Currency).Append('\n'); + if (Calendar.Count > Sessions.Count) + { + text.Append(CultureInfo.InvariantCulture, $"calendar {Calendar.Count} {Calendar[^1]:yyyy-MM-dd}\n"); + } + foreach (var i in Instruments) { var s = i.Spec; - text.Append(CultureInfo.InvariantCulture, $"{s.Venue}|{s.Symbol}|{s.AssetClass}|{s.QuoteCurrency}|{s.TickSize}|{s.LotSize}|{s.MinSize}|{s.MinNotional}|{s.Fractionable}\n"); + text.Append(CultureInfo.InvariantCulture, $"{s.Venue}|{s.Symbol}|{s.AssetClass}|{s.QuoteCurrency}|{s.TickSize}|{s.LotSize}|{s.MinSize}|{s.MinNotional}|{s.Fractionable}"); + text.Append(DataOnly.Contains(i.Symbol) ? "|data\n" : "\n"); foreach (var b in i.Bars) { text.Append(CultureInfo.InvariantCulture, $"{b.Day:yyyy-MM-dd},{b.Open:R},{b.High:R},{b.Low:R},{b.Close:R},{b.Volume:R}\n"); diff --git a/src/Anubis/Backtest/Engine.cs b/src/Anubis/Backtest/Engine.cs index 4c24d5f..ad10bc4 100644 --- a/src/Anubis/Backtest/Engine.cs +++ b/src/Anubis/Backtest/Engine.cs @@ -22,6 +22,12 @@ public sealed record BacktestOptions /// The risk engine of SPEC 9. Until Phase 5 it lets everything through. public IIntentStage Risk { get; init; } = PassThroughStage.Risk; + + ///+ /// The strategy's share of the bot's total capital (SPEC 8.6, 9.2): the reference equity is the strategy's equity + /// divided by it. Null means the strategy is the whole bot. + /// + public decimal? ReferenceShare { get; init; } } ///A book to start from: a state recorded live, for the one-step comparison of SPEC 12.3. @@ -93,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"; + + ///+ /// Prefix of the notes that count the codes of the correctives and of the risk engine on the intents of each close + /// ( + public const string AdjustedPrefix = "adjusted:"; } ///adjusted:trade_risk_limit ): how often a rule changed what the strategy asked for. + ///@@ -105,7 +117,7 @@ public static class BacktestReasons public static class BacktestEngine { /// public sealed partial class Laboratory : IDisposable { - public const int MaxSymbols = 20; + public const int MaxSymbols = 60; public const int MaxVariants = 200; @@ -143,7 +143,10 @@ public sealed partial class Laboratory : IDisposable TrialValidation.Default, TrialThresholds.Default, BacktestEngine.Version, - now); + now) + { + ReferenceShare = StrategyPipeline.DefaultShare(family.Id), + }; var variants = ParameterGrid.Of(family, plan.Grid).Count; if (variants == 0) { @@ -261,29 +264,45 @@ public sealed partial class Laboratory : IDisposable { var instrument = await catalog.FindAsync(data.Venue, symbol, cancellationToken).ConfigureAwait(false) ?? throw new InvalidOperationException($"Strumento sconosciuto: {symbol} su {data.Venue}."); - var daily = await bars.DailyAsync(instrument.Id, data.From, data.To, cancellationToken).ConfigureAwait(false); + var daily = await bars.DailyAsync(instrument.Id, data.HistoryStart(), data.To, cancellationToken).ConfigureAwait(false); var events = instrument.IsCrypto ? [] : await actions.ForSymbolAsync(symbol, cancellationToken).ConfigureAwait(false); - instruments.Add(new BacktestInstrument(instrument.Spec, daily, [.. events.Where(a => a.ExDate > data.From && a.ExDate <= data.To)], "barre raccolte")); + instruments.Add(new BacktestInstrument(instrument.Spec, daily, [.. events.Where(a => a.ExDate > data.HistoryStart() && a.ExDate <= data.To)], "barre raccolte")); } } else { - var store = new ResearchStore(researchRoot); - var from = new DateTimeOffset(data.From.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); - var to = new DateTimeOffset(data.To.AddDays(1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); - foreach (var symbol in data.Symbols) - { - var daily = new ListChanges when the engine computes differently: plans record it, so a report says which engine made it. - public const string Version = "1"; + public const string Version = "2"; public static BacktestRun Run(IStrategy strategy, BacktestDataset data, BacktestOptions? options = null, PortfolioState? start = null) { @@ -203,7 +215,10 @@ public static class BacktestEngine public decimal Fees { get; set; } } - private sealed record Pending(string Symbol, OrderSide Side, decimal Quantity, bool Exit, decimal? Stop, string Reason); + private sealed record Pending(string Symbol, OrderSide Side, decimal Quantity, bool Exit, decimal? Stop, string Reason) + { + public decimal? StopOffset { get; init; } + } private sealed class Simulation { @@ -216,6 +231,7 @@ public static class BacktestEngine private readonly Dictionary_lastClose = new(StringComparer.Ordinal); private readonly Dictionary _actionsDoneThrough = new(StringComparer.Ordinal); private readonly List _equity = []; + private readonly List _history = []; private readonly List _fills = []; private readonly List _trades = []; private readonly List _decisions = []; @@ -358,19 +374,44 @@ public static class BacktestEngine MarkOn(day); var invested = Invested(); _equity.Add(new EquityPoint(day, _cash + invested, _cash, invested)); + _history.Add(new EquityMark(day, _cash + invested, invested)); var record = Decide(day, at); _decisions.Add(record); - Plan(day, record.Final); + 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)) + { + if (_positions.TryGetValue(exit.Symbol, out var p) && _lastClose.TryGetValue(exit.Symbol, out var close)) + { + Sell(day, exit.Symbol, p.Quantity, close, exit.Reason, exit: true); + _pending.Remove(exit.Symbol); + } + } + + Plan(day, [.. record.Final.Where(i => !(i.AtClose && i.TargetWeight == 0m))]); } public DecisionRecord Decide(DateOnly day, DateTimeOffset at) { - var available = _data.Instruments.Where(i => i.CountThrough(day) > 0).Select(i => i.Symbol).ToList(); - var universe = _strategy.Universe(new UniverseContext(day, available)); + var available = _data.Tradable.Where(i => i.CountThrough(day) > 0).Select(i => i.Symbol).ToList(); + BarSeries Bars(string s) => _data[s]?.SeriesThrough(day) ?? BarSeries.Empty; + var universe = _strategy.Universe(new UniverseContext(day, available) { Bars = Bars, Spec = s => _data[s]?.Spec }); var equity = _cash + Invested(); var holdings = _positions.ToDictionary(p => p.Key, p => new Holding(p.Value.Quantity, p.Value.AveragePrice, p.Value.Stop, p.Value.EnteredOn), StringComparer.Ordinal); - var context = new StrategyContext(day, at, universe, new PortfolioView(_cash, equity, holdings), - s => _data[s]?.SeriesThrough(day) ?? BarSeries.Empty, s => _data[s]?.Spec); + var context = new StrategyContext(day, at, universe, new PortfolioView(_cash, equity, holdings), Bars, s => _data[s]?.Spec) + { + NextSession = _data.NextSession(day), + ReferenceEquity = _options.ReferenceShare is > 0m and var share ? equity / share : equity, + PeriodsPerYear = _data.PeriodsPerYear, + History = _history, + }; var proposed = _strategy.Decide(context); var final = proposed; foreach (var stage in _options.Correctives) @@ -438,7 +479,7 @@ public static class BacktestEngine var difference = target - current; if (difference > 0m) { - _pending[intent.Symbol] = new Pending(intent.Symbol, OrderSide.Buy, difference, Exit: false, stop, intent.Reason); + _pending[intent.Symbol] = new Pending(intent.Symbol, OrderSide.Buy, difference, Exit: false, stop, intent.Reason) { StopOffset = intent.StopOffset }; } else if (difference < 0m) { @@ -480,6 +521,11 @@ public static class BacktestEngine p.AveragePrice = DbValues.Money(((p.Quantity * p.AveragePrice) + fill.Gross) / (p.Quantity + fill.Quantity)); p.Quantity += fill.Quantity; p.Stop = order.Stop ?? p.Stop; + if (p.Stop is null && order.StopOffset is > 0m and var offset && price - offset > 0m) + { + // A distance from the price obtained: the stop of a new position (SPEC 8.2, 8.3). + p.Stop = OrderRules.StopPrice(price - offset, OrderRules.TickOf(spec, price - offset)); + } p.Trade.Bought += fill.Gross; p.Trade.CashFlow += fill.CashDelta; p.Trade.Fees += fill.FeeValue; diff --git a/src/Anubis/Backtest/Laboratory.cs b/src/Anubis/Backtest/Laboratory.cs index 4787daa..0309736 100644 --- a/src/Anubis/Backtest/Laboratory.cs +++ b/src/Anubis/Backtest/Laboratory.cs @@ -46,7 +46,7 @@ public static class TrialRequestErrors /// (); - await foreach (var b in store.ReadAsync(data.Venue, symbol, Timeframes.Day, from, to, cancellationToken).ConfigureAwait(false)) - { - daily.Add(new DailyBar(DateOnly.FromDateTime(b.OpensAt.UtcDateTime), (double)b.Open, (double)b.High, (double)b.Low, (double)b.Close, (double)b.Volume)); - } - - instruments.Add(new BacktestInstrument(ResearchSpec(data.Venue, symbol), daily, null, "storico di ricerca")); - } + return await LoadResearchAsync(researchRoot, data, cancellationToken).ConfigureAwait(false); } - var empty = instruments.FirstOrDefault(i => i.Bars.Count == 0); + return Checked(instruments, data); + } + + /// The bars of a trial on the research history: no database needed (the protocol runs from the command line). + public static async TaskLoadResearchAsync(string researchRoot, TrialData data, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(data); + var instruments = new List (); + var store = new ResearchStore(researchRoot); + var from = new DateTimeOffset(data.HistoryStart().ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + var to = new DateTimeOffset(data.To.AddDays(1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + var source = data.Venue == EuroHistory.Venue ? "storico Binance convertito in euro" : "storico di ricerca"; + foreach (var symbol in data.Symbols) + { + var daily = new List (); + await foreach (var b in store.ReadAsync(data.Venue, symbol, Timeframes.Day, from, to, cancellationToken).ConfigureAwait(false)) + { + daily.Add(new DailyBar(DateOnly.FromDateTime(b.OpensAt.UtcDateTime), (double)b.Open, (double)b.High, (double)b.Low, (double)b.Close, (double)b.Volume)); + } + + instruments.Add(new BacktestInstrument(ResearchSpec(data.Venue, symbol), daily, null, source)); + } + + return Checked(instruments, data); + } + + private static BacktestDataset Checked(List instruments, TrialData data) + { + var empty = instruments.FirstOrDefault(i => !i.Bars.Any(b => b.Day >= data.From && b.Day <= data.To)); if (empty is not null) { throw new InvalidOperationException($"Nessuna barra giornaliera per {empty.Symbol} tra il {data.From:dd/MM/yyyy} e il {data.To:dd/MM/yyyy}."); diff --git a/src/Anubis/Backtest/LookAhead.cs b/src/Anubis/Backtest/LookAhead.cs index 7651682..72d097e 100644 --- a/src/Anubis/Backtest/LookAhead.cs +++ b/src/Anubis/Backtest/LookAhead.cs @@ -62,7 +62,7 @@ public static class LookAheadCheck /// Intents as text, with stops to nine significant digits: adjusted prices may differ in the last bit. private static string Describe(IReadOnlyListintents) => string.Join(" | ", intents.Select(i => string.Create( CultureInfo.InvariantCulture, - $"{i.Symbol} {i.TargetWeight?.ToString(CultureInfo.InvariantCulture) ?? "keep"} {(i.Stop is { } s ? ((double)s).ToString("G9", CultureInfo.InvariantCulture) : "-")} {i.Reason}"))); + $"{i.Symbol} {(i.TargetWeight is { } w ? ((double)w).ToString("G9", CultureInfo.InvariantCulture) : "keep")} {(i.Stop is { } s ? ((double)s).ToString("G9", CultureInfo.InvariantCulture) : "-")} {(i.StopOffset is { } o ? ((double)o).ToString("G9", CultureInfo.InvariantCulture) : "-")}{(i.AtClose ? " close" : "")} {i.Reason}"))); } /// How the live intent and the backtest intent for one instrument compare (SPEC 12.3). diff --git a/src/Anubis/Backtest/Protocol.cs b/src/Anubis/Backtest/Protocol.cs new file mode 100644 index 0000000..369c097 --- /dev/null +++ b/src/Anubis/Backtest/Protocol.cs @@ -0,0 +1,378 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using Anubis.Core; +using Anubis.Data; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Backtest; + +///+/// The Binance USDT archives turned into euro (SPEC 8.1): the EUR pairs of OKX start in November 2023, so the years +/// before use the USDT history divided by the ECB EUR/USD rate of the day, one USDT counted as one dollar. The +/// converted series live in the research history under their own venue, so a trial on them can be planned again. +/// +public static class EuroHistory +{ + public const string Venue = "binance_eur"; + + ///A rate older than this is not used: the ECB never skips more than a long holiday weekend. + public static readonly int MaxRateAgeDays = 7; + + ///+ /// A hole longer than this in a coin's daily series ends it: what comes after is a relaunch under the same ticker + /// (LUNA after May 2022), not the coin the earlier bars describe. + /// + public static readonly int MaxGapDays = 7; + + ///+ public static string SymbolOf(string usdtSymbol) + { + ArgumentNullException.ThrowIfNull(usdtSymbol); + return usdtSymbol.EndsWith("USDT", StringComparison.Ordinal) && usdtSymbol.Length > 4 + ? usdtSymbol[..^4] + "EUR" + : throw new ArgumentException("Not a USDT pair: " + usdtSymbol, nameof(usdtSymbol)); + } + + /// BTCUSDT becomesBTCEUR .+ /// 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 + public static IReadOnlyListdays exists. The series stops at the first hole + /// longer than days. + /// Convert(IEnumerable bars, IReadOnlyList eurUsd) + { + ArgumentNullException.ThrowIfNull(bars); + ArgumentNullException.ThrowIfNull(eurUsd); + var rates = eurUsd.Where(r => r.Base == "EUR" && r.Quote == "USD" && r.Rate > 0m).OrderBy(r => r.Date).ToList(); + var result = new List (); + var k = -1; + DateTimeOffset? previous = null; + foreach (var bar in bars.OrderBy(b => b.OpensAt)) + { + if (previous is { } p && bar.OpensAt - p > TimeSpan.FromDays(MaxGapDays)) + { + break; + } + + previous = bar.OpensAt; + var day = DateOnly.FromDateTime(bar.OpensAt.UtcDateTime); + while (k + 1 < rates.Count && rates[k + 1].Date < day) + { + k++; + } + + if (k < 0 || rates[k].Date < day.AddDays(-MaxRateAgeDays)) + { + continue; + } + + var rate = rates[k].Rate; + result.Add(new ResearchBar(bar.OpensAt, Round(bar.Open / rate), Round(bar.High / rate), Round(bar.Low / rate), Round(bar.Close / rate), bar.Volume) + { + QuoteVolume = bar.QuoteVolume is { } q ? Round(q / rate) : null, + Trades = bar.Trades, + }); + } + + return result; + } + + /// Converts every daily USDT series of the Binance archives in the store. Returns the symbols written. + public static async Task> ConvertAllAsync(ResearchStore store, IReadOnlyList eurUsd, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(store); + var written = new List (); + foreach (var (_, symbol, _) in store.Series().Where(s => s.Venue == Venues.Binance && s.Timeframe == Timeframes.Day && s.Symbol.EndsWith("USDT", StringComparison.Ordinal))) + { + var bars = new List (); + await foreach (var bar in store.ReadAsync(Venues.Binance, symbol, Timeframes.Day, Ever.From, Ever.To, cancellationToken).ConfigureAwait(false)) + { + bars.Add(bar); + } + + var converted = Convert(bars, eurUsd); + if (converted.Count > 0) + { + await store.WriteAsync(Venue, SymbolOf(symbol), Timeframes.Day, converted, cancellationToken).ConfigureAwait(false); + written.Add(SymbolOf(symbol)); + } + } + + return written; + } + + // Twelve decimals keep seven significant digits even for coins priced at a hundred-thousandth of a euro. + private static decimal Round(decimal value) => Math.Round(value, 12, MidpointRounding.ToEven); + + private static class Ever + { + public static readonly DateTimeOffset From = new(2009, 1, 1, 0, 0, 0, TimeSpan.Zero); + + public static readonly DateTimeOffset To = new(2100, 1, 1, 0, 0, 0, TimeSpan.Zero); + } +} + +/// A trial of the protocol: which universe, its report and the daily returns of the chosen variant. +public sealed record ProtocolRun(string Name, string Description, TrialPlan Plan, BacktestReport Report, IReadOnlyListDailyReturns, decimal ExpectedSlippageBp); + +/// What the protocol of a strategy concluded: the outcome file and the trials behind it. +public sealed record ProtocolOutcome(Qualification Qualification, IReadOnlyListRuns); + +/// +/// The anti-illusion protocol of SPEC 12.2 for +public static class CryptoTrendProtocol +{ + public const string Strategy = StrategyNames.CryptoTrend; + + public const string ReportPath = "docs/backtests/crypto_trend.md"; + + public const decimal Capital = 10_000m; + + ///crypto_trend , run from the command line on the research +/// history: it must pass twice (SPEC 8.1), on the broad universe and on BTC, ETH and SOL alone. Everything is fixed +/// before the run: dates, capital, grid, costs, thresholds. The result is written whatever it is. +///Two years of Binance history before this day are enough for the longest period (360) and the 400 days of age. + public static readonly DateOnly From = new(2019, 1, 1); + + public static readonly IReadOnlyListNarrow = ["BTCEUR", "ETHEUR", "SOLEUR"]; + + /// + /// The USDT pairs downloaded from the Binance archives: every coin that was among the ten most traded at some time + /// since 2018, including those later delisted (LUNA, FTT, BCC, VEN, XMR...), so the past universe is not chosen + /// with hindsight. Stablecoins are left out: the strategy excludes them anyway. A pair without archives is skipped. + /// + public static readonly IReadOnlyListArchives = + [ + "BTCUSDT", "ETHUSDT", "BNBUSDT", "XRPUSDT", "ADAUSDT", "SOLUSDT", "DOGEUSDT", "LTCUSDT", "BCCUSDT", "BCHABCUSDT", "BCHUSDT", "BCHSVUSDT", + "EOSUSDT", "TRXUSDT", "ETCUSDT", "LINKUSDT", "DOTUSDT", "MATICUSDT", "POLUSDT", "AVAXUSDT", "LUNAUSDT", "FTTUSDT", "SHIBUSDT", "FILUSDT", + "ATOMUSDT", "UNIUSDT", "NEOUSDT", "XLMUSDT", "VENUSDT", "VETUSDT", "SANDUSDT", "APEUSDT", "GMTUSDT", "NEARUSDT", "PEPEUSDT", "WIFUSDT", + "SUIUSDT", "ARBUSDT", "OPUSDT", "ORDIUSDT", "ONTUSDT", "IOTAUSDT", "QTUMUSDT", "ICXUSDT", "XMRUSDT", "DASHUSDT", "ZECUSDT", "TONUSDT", "TRUMPUSDT", + ]; + + /// Length of the expected path of the outcome: one year of daily closes. + public const int PathDays = 365; + + public static async TaskRunAsync(string researchRoot, DateOnly to, DateTimeOffset now, Action ? progress, CancellationToken cancellationToken) + { + var store = new ResearchStore(researchRoot); + var broad = new List (); + foreach (var (_, symbol, _) in store.Series().Where(s => s.Venue == EuroHistory.Venue && s.Timeframe == Timeframes.Day)) + { + // Every converted pair goes in: the strategy picks its top 10 month by month, among coins that died too. + if (await HasBarsAsync(store, symbol, to, cancellationToken).ConfigureAwait(false)) + { + broad.Add(symbol); + } + } + + if (Narrow.Any(s => !broad.Contains(s))) + { + throw new InvalidOperationException("Mancano gli storici di BTC, ETH o SOL in euro: scarica prima gli archivi Binance e il cambio BCE."); + } + + var family = StrategyCatalog.Find(Strategy) ?? throw new InvalidOperationException("crypto_trend non è nel catalogo."); + var first = await RunOneAsync(family, "Universo ampio", $"Le 10 monete con più scambi, scelte ogni mese tra {broad.Count} coppie (anche quelle poi chiuse).", + broad, to, now, researchRoot, PriorTrials.None, progress, cancellationToken).ConfigureAwait(false); + var prior = new PriorTrials(1, first.Report.Variants.Count, [.. first.Report.Variants.Select(v => v.Sharpe)]); + var second = await RunOneAsync(family, "BTC, ETH e SOL", "Solo le tre coppie in euro con la liquidità migliore.", + Narrow, to, now, researchRoot, prior, progress, cancellationToken).ConfigureAwait(false); + List runs = [first, second]; + return new ProtocolOutcome(QualificationOf(runs), runs); + } + + /// The outcome file: passed only when every trial passed; measures from the broad universe, the one traded live. + public static Qualification QualificationOf(IReadOnlyListruns) + { + ArgumentNullException.ThrowIfNull(runs); + var main = runs[0]; + var passed = runs.All(r => r.Report.Passed); + var it = CultureInfo.GetCultureInfo("it-IT"); + string verdict; + if (passed) + { + verdict = "Protocollo superato su entrambi gli universi: parte in simulazione."; + } + else + { + var failures = runs.Where(r => !r.Report.Passed) + .Select(r => r.Name + ": " + string.Join("; ", r.Report.Checks.Where(c => c.Passed == false).Select(c => Describe(c, it)))); + verdict = "Protocollo non superato. " + string.Join(". ", failures) + ". Resta in osservazione."; + } + + var taker = PaperOptions.Okx().TakerFee; + return new Qualification + { + Passed = passed, + 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), + ExpectedPathP5 = [.. PathBootstrap.Percentile(main.DailyReturns, PathDays, 0.05, PathBootstrap.Paths, PathBootstrap.Block, PathBootstrap.Seed) + .Select(x => Math.Round(x, 4))], + }; + } + + /// A failed check in plain Italian, e.g. "calo massimo 38,2%, oltre il 25%". + public static string Describe(ReportCheck check, IFormatProvider culture) + { + ArgumentNullException.ThrowIfNull(check); + var value = check.Value is not { } v ? "non calcolabile" + : check.Unit switch + { + "percent" => string.Create(culture, $"{v * 100:0.0}%"), + "money" => string.Create(culture, $"{v:#,0.00} €"), + "count" => string.Create(culture, $"{v:0}"), + _ => string.Create(culture, $"{v:0.000}"), + }; + var threshold = check.Unit == "percent" ? string.Create(culture, $"{check.Threshold * 100:0}%") : string.Create(culture, $"{check.Threshold:0.00}"); + return $"{check.Name.ToLower(CultureInfo.GetCultureInfo("it-IT"))} {value}, serve {check.Comparison} {threshold}"; + } + + private static async TaskRunOneAsync(IStrategyFamily family, string name, string description, IReadOnlyList symbols, DateOnly to, + DateTimeOffset now, string researchRoot, PriorTrials prior, Action ? progress, CancellationToken cancellationToken) + { + var request = new TrialRequest(family.Id, TrialSources.Research, EuroHistory.Venue, symbols, From, to, Capital, null); + var (plan, _) = Laboratory.BuildPlan(request, now); + var json = plan.ToJson(); + var hash = TrialPlan.Hash(json); + var data = await Laboratory.LoadResearchAsync(researchRoot, plan.Data, cancellationToken).ConfigureAwait(false); + + // The id comes from the plan, so the same plan on the same data writes the same report. + var id = new Guid(SHA256.HashData(Encoding.UTF8.GetBytes(hash)).AsSpan(0, 16)); + var (report, _) = TrialRunner.Run(id, plan, hash, family, data, prior, now, text => progress?.Invoke(name + ": " + text), cancellationToken); + + // The chosen variant again, for its daily returns and the slippage of what it traded. + var variant = ParameterGrid.Of(family, plan.Grid).First(v => v.ToString() == report.Chosen); + var options = StrategyPipeline.For(family.Id, data, new BacktestOptions { InitialCapital = plan.InitialCapital, From = plan.Data.From, To = plan.Data.To }, plan.ReferenceShare); + var run = BacktestEngine.Run(family.Create(variant.Parameters), data, options); + var specs = data.Instruments.ToDictionary(i => i.Symbol, i => i.Spec, StringComparer.Ordinal); + var traded = run.Trades.Sum(t => t.Invested); + var slippage = traded > 0m + ? Math.Round(run.Trades.Sum(t => t.Invested * PaperBroker.SlippageBp(specs.GetValueOrDefault(t.Symbol))) / traded, 2) + : PaperBroker.SlippageBp(null); + return new ProtocolRun(name, description, plan, report, run.DailyReturns(), slippage); + } + + private static async Task HasBarsAsync(ResearchStore store, string symbol, DateOnly to, CancellationToken cancellationToken) + { + var from = new DateTimeOffset(From.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + var end = new DateTimeOffset(to.AddDays(1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + await foreach (var _ in store.ReadAsync(EuroHistory.Venue, symbol, Timeframes.Day, from, end, cancellationToken).ConfigureAwait(false)) + { + return true; + } + + return false; + } +} + +/// +/// The expected path of SPEC 12.3: a stationary block bootstrap of the backtest's daily returns (blocks keep the +/// clustering of volatility), and for each day from the start the given percentile of the cumulative result. The seed +/// is fixed, so the same returns always give the same path. +/// +public static class PathBootstrap +{ + public const int Paths = 2000; + + public const int Block = 20; + + public const int Seed = 20_260_101; + + public static IReadOnlyListPercentile(IReadOnlyList returns, int days, double percentile, int paths, int block, int seed) + { + ArgumentNullException.ThrowIfNull(returns); + ArgumentOutOfRangeException.ThrowIfLessThan(days, 1); + ArgumentOutOfRangeException.ThrowIfLessThan(paths, 1); + ArgumentOutOfRangeException.ThrowIfLessThan(block, 1); + if (returns.Count == 0) + { + return [.. Enumerable.Repeat(0d, days)]; + } + + var random = new Random(seed); + var cumulative = new double[days][]; + for (var d = 0; d < days; d++) + { + cumulative[d] = new double[paths]; + } + + for (var p = 0; p < paths; p++) + { + var value = 1d; + var index = random.Next(returns.Count); + for (var d = 0; d < days; d++) + { + // A new block starts with probability 1/block: blocks of geometric length, mean "block" days. + if (d > 0 && random.NextDouble() < 1d / block) + { + index = random.Next(returns.Count); + } + else if (d > 0) + { + index = (index + 1) % returns.Count; + } + + value *= 1d + returns[index]; + cumulative[d][p] = value - 1d; + } + } + + var result = new double[days]; + for (var d = 0; d < days; d++) + { + Array.Sort(cumulative[d]); + var rank = Math.Clamp((int)Math.Floor(percentile * (paths - 1)), 0, paths - 1); + result[d] = cumulative[d][rank]; + } + + return result; + } +} + +/// +/// The outcome files of +public static class BacktestOutcomes +{ + public const string ResourcePrefix = "Anubis.Backtests."; + + public static Qualification? Find(string strategy) + { + using var stream = typeof(BacktestOutcomes).Assembly.GetManifestResourceStream(ResourcePrefix + strategy + ".outcome.json"); + return stream is null ? null : JsonSerializer.Deserializedocs/backtests/ , built into the program: loaded at the first start, they decide +/// whether a base strategy starts in simulation or stays in observation (SPEC 12.3). +///(stream, Qualification.Json); + } + + private static readonly JsonSerializerOptions Indented = new(Qualification.Json) { WriteIndented = true }; + + public static string ToJson(Qualification qualification) => JsonSerializer.Serialize(qualification, Indented) + "\n"; +} + +/// +/// The stock strategies wait for the Alpaca history (SPEC 8.2, 8.3): without the keys there are no adjusted daily +/// bars of the S&P 500 members, so the protocol cannot run and they stay in observation. The outcome file says so. +/// +public static class EquityProtocol +{ + public static readonly IReadOnlyListExplanation = + [ + "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 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() + { + Passed = false, + Verdict = "In attesa delle chiavi Alpaca: senza lo storico delle azioni il backtest non si può fare, quindi la strategia resta in osservazione.", + Report = "docs/backtests/" + strategy + ".md", + }; +} diff --git a/src/Anubis/Backtest/ProtocolReport.cs b/src/Anubis/Backtest/ProtocolReport.cs new file mode 100644 index 0000000..fe0dc52 --- /dev/null +++ b/src/Anubis/Backtest/ProtocolReport.cs @@ -0,0 +1,220 @@ +using System.Globalization; +using System.Text; +using Anubis.Trading; + +namespace Anubis.Backtest; + +/// +/// The report of +public static class ProtocolReport +{ + private static readonly CultureInfo It = CultureInfo.GetCultureInfo("it-IT"); + + public static string Markdown(ProtocolOutcome outcome, string title, IReadOnlyListdocs/backtests/ in plain Italian (SPEC 12.2 point 6): for each trial the figures of the chosen +/// variant against buy and hold, by year, at single, double and triple costs, the validations, the checks and what +/// the backtest does not model. It is written whatever the outcome. +///dataNotes, string command) + { + ArgumentNullException.ThrowIfNull(outcome); + ArgumentNullException.ThrowIfNull(dataNotes); + var q = outcome.Qualification; + var first = outcome.Runs[0].Report; + var b = new StringBuilder(); + b.Append("# Backtest di `").Append(first.Strategy).Append("` (").Append(first.StrategyName).AppendLine(")").AppendLine(); + b.Append("**Esito: ").Append(q.Passed ? "superato" : "non superato").Append(".** ").AppendLine(q.Verdict).AppendLine(); + b.AppendLine(Text($"Calcolato il {first.ComputedAt:yyyy-MM-dd} con la versione {first.StrategyVersion} della strategia. Soglie, griglia dei parametri, costi e date erano fissati prima del calcolo (SPEC 12.2) e non sono stati cambiati dopo.")) + .AppendLine(); + b.Append("Per rifarlo: `").Append(command).AppendLine("`. Il file dell'esito, letto dal bot al primo avvio, è `docs/backtests/" + first.Strategy + ".outcome.json`.").AppendLine(); + + b.AppendLine("## Dati").AppendLine(); + foreach (var note in dataNotes) + { + b.Append("- ").AppendLine(note); + } + + b.AppendLine(); + b.AppendLine("## Riepilogo").AppendLine(); + b.AppendLine("| Prova | Variante scelta | Rendimento annuo | Calo massimo | Netto a costi doppi | DSR | PBO | Esito |"); + b.AppendLine("|---|---|---:|---:|---:|---:|---:|---|"); + foreach (var run in outcome.Runs) + { + var r = run.Report; + var doubled = r.Costs.FirstOrDefault(c => c.Multiplier == 2m); + b.Append("| ").Append(run.Name).Append(" | `").Append(r.Chosen).Append("` | ").Append(Pct(r.Metrics.AnnualReturn)).Append(" | ").Append(Pct(-r.Metrics.MaxDrawdown)) + .Append(" | ").Append(doubled is null ? "—" : Money(doubled.NetResult, r.Currency)).Append(" | ").Append(r.DeflatedSharpe.Value.ToString("0.000", It)) + .Append(" | ").Append(r.Overfitting is { } o ? o.Probability.ToString("0.000", It) : "—").Append(" | ").Append(r.Passed ? "superata" : "non superata").AppendLine(" |"); + } + + b.AppendLine(); + b.AppendLine("## Cosa conserva il bot").AppendLine(); + b.AppendLine(Text($"- Calo massimo del backtest: {Pct(-(double)q.MaxDrawdown)}. Dal vivo, un calo oltre 1,5 volte questo riporta la strategia indietro (SPEC 12.3).")); + b.AppendLine(Text($"- Scostamento di prezzo previsto: {q.ExpectedSlippageBp.ToString("0.##", It)} punti base; costo stimato di andata e ritorno {Pct((double)q.RoundTripCost, 2)}.")); + if (q.ExpectedPathP5.Count > 0) + { + b.AppendLine(Text($"- Percorso atteso al 5° percentile (ricampionamento a blocchi dei rendimenti giornalieri): {Pct(q.ExpectedPathP5[Math.Min(29, q.ExpectedPathP5.Count - 1)])} dopo 30 giorni, {Pct(q.ExpectedPathP5[Math.Min(89, q.ExpectedPathP5.Count - 1)])} dopo 90, {Pct(q.ExpectedPathP5[^1])} dopo {q.ExpectedPathP5.Count}. Venti sedute di fila sotto questo percorso riportano la strategia indietro.")); + } + + b.AppendLine(); + foreach (var run in outcome.Runs) + { + Trial(b, run); + } + + b.AppendLine("## Cosa il backtest non rappresenta").AppendLine(); + foreach (var line in first.Limitations) + { + b.Append("- ").AppendLine(line); + } + + return b.ToString(); + } + + /// The report of a strategy whose backtest cannot run yet, with what it waits for. + public static string Waiting(string strategy, string name, Qualification qualification, IReadOnlyListlines) + { + ArgumentNullException.ThrowIfNull(qualification); + ArgumentNullException.ThrowIfNull(lines); + var b = new StringBuilder(); + b.Append("# Backtest di `").Append(strategy).Append("` (").Append(name).AppendLine(")").AppendLine(); + b.Append("**Esito: in attesa.** ").AppendLine(qualification.Verdict).AppendLine(); + foreach (var line in lines) + { + b.AppendLine(line).AppendLine(); + } + + return b.ToString(); + } + + private static void Trial(StringBuilder b, ProtocolRun run) + { + var r = run.Report; + var m = r.Metrics; + var h = r.Benchmark; + // Validations and variants keep the Sharpe of one session: shown per year, like the metrics above. + var annual = Math.Sqrt(r.PeriodsPerYear); + b.Append("## ").AppendLine(run.Name).AppendLine(); + b.AppendLine(run.Description).AppendLine(); + b.AppendLine(Text($"Dal {m.From:dd/MM/yyyy} al {m.To:dd/MM/yyyy}, {r.Sessions} chiusure giornaliere, capitale iniziale {Money(m.InitialCapital, r.Currency)}. Variante scelta: `{r.Chosen}` (la zona della griglia dove il risultato cambia meno, non la migliore). Impronta del piano `{r.PlanHash[..12]}`, dei dati `{r.DataFingerprint[..12]}`.")) + .AppendLine(); + + b.AppendLine("| | Strategia | Comprare e tenere |").AppendLine("|---|---:|---:|"); + Row(b, "Risultato netto", Money(m.NetResult, r.Currency), Money(h.NetResult, r.Currency)); + Row(b, "Rendimento totale", Pct(m.TotalReturn), Pct(h.TotalReturn)); + Row(b, "Rendimento annuo", Pct(m.AnnualReturn), Pct(h.AnnualReturn)); + Row(b, "Volatilità annua", Pct(m.Volatility), Pct(h.Volatility)); + Row(b, "Calo massimo", Pct(-m.MaxDrawdown) + Text($" ({m.DrawdownPeak:MM/yyyy} → {m.DrawdownLow:MM/yyyy})"), Pct(-h.MaxDrawdown)); + Row(b, "Sharpe annuo", Num(m.Sharpe), Num(h.Sharpe)); + Row(b, "Operazioni chiuse", m.Trades.ToString(It), h.Trades.ToString(It)); + Row(b, "Operazioni in guadagno", Pct(m.WinRate), "—"); + Row(b, "Rapporto guadagni/perdite", m.ProfitFactor is { } pf ? Num(pf) : "—", "—"); + Row(b, "Commissioni pagate", Money(m.Fees, r.Currency), Money(h.Fees, r.Currency)); + Row(b, "Tempo investito", Pct(m.Exposure), Pct(h.Exposure)); + b.AppendLine(); + + b.AppendLine("**Per anno**").AppendLine(); + b.AppendLine("| Anno | Strategia | Comprare e tenere |").AppendLine("|---|---:|---:|"); + var held = h.Years.ToDictionary(y => y.Year); + foreach (var y in m.Years) + { + Row(b, y.Year.ToString(CultureInfo.InvariantCulture), Pct(y.Return), held.TryGetValue(y.Year, out var hy) ? Pct(hy.Return) : "—"); + } + + b.AppendLine(); + b.AppendLine("**Sensibilità ai costi** (commissioni e scostamento moltiplicati insieme)").AppendLine(); + b.AppendLine("| Costi | Risultato netto | Rendimento totale | Sharpe annuo | Calo massimo | Commissioni |").AppendLine("|---|---:|---:|---:|---:|---:|"); + foreach (var c in r.Costs) + { + b.AppendLine(Text($"| ×{c.Multiplier:0} | {Money(c.NetResult, r.Currency)} | {Pct(c.TotalReturn)} | {Num(c.Sharpe)} | {Pct(-c.MaxDrawdown)} | {Money(c.Fees, r.Currency)} |")); + } + + b.AppendLine(); + b.AppendLine("**Convalide**").AppendLine(); + if (r.WalkForward is { } wf) + { + b.AppendLine(Text($"- Finestre che avanzano ({wf.Windows.Count}, con {wf.Purge} giorni di stacco): rendimento fuori campione {Pct(wf.Return)}, Sharpe annuo {Num(wf.Sharpe * annual)}.")); + } + + if (r.Combinatorial is { } cv) + { + b.AppendLine(Text($"- K-fold purgato combinatorio ({cv.Groups} gruppi, {cv.TestGroups} di prova, {cv.Splits} divisioni): Sharpe annuo medio dei percorsi {Num(cv.MeanSharpe * annual)}, peggiore {Num(cv.WorstSharpe * annual)}, percorsi positivi {Pct(cv.PositiveShare)}.")); + } + + b.AppendLine(Text($"- Deflated Sharpe Ratio {Num(r.DeflatedSharpe.Value)}, contando {r.TrialsCounted} varianti provate in tutto.")); + b.AppendLine(r.Overfitting is { } pbo + ? Text($"- Probabilità di sovra-adattamento (PBO) {Num(pbo.Probability)}, su {pbo.Combinations} combinazioni di {pbo.Variants} varianti.") + : "- Probabilità di sovra-adattamento: non calcolabile con una sola variante."); + b.AppendLine(Text($"- Sguardo in avanti: {r.LookAhead.Decisions} decisioni rifatte tagliando i dati in {r.LookAhead.Cutoffs.Count} punti, {r.LookAhead.Changed} cambiate.")); + b.AppendLine(); + + b.AppendLine("**Soglie**").AppendLine(); + b.AppendLine("| Controllo | Valore | Soglia | Esito |").AppendLine("|---|---:|---:|---|"); + foreach (var c in r.Checks) + { + var value = c.Value is not { } v ? "—" : c.Unit switch + { + "percent" => Pct(v), + "money" => Money((decimal)v, r.Currency), + "count" => v.ToString("0", It), + _ => v.ToString("0.000", It), + }; + var threshold = c.Unit == "percent" ? Pct(c.Threshold, 0) : c.Unit == "money" ? Money((decimal)c.Threshold, r.Currency) : c.Threshold.ToString("0.##", It); + b.AppendLine(Text($"| {c.Name} | {value} | {c.Comparison} {threshold} | {(c.Passed is null ? "non si applica" : c.Passed.Value ? "superato" : "**non superato**")} |")); + } + + b.AppendLine(); + b.AppendLine("**Varianti della griglia**").AppendLine(); + b.AppendLine("| Parametri | Sharpe annuo | Stabilità della zona | Risultato netto | Calo massimo | Operazioni |").AppendLine("|---|---:|---:|---:|---:|---:|"); + foreach (var v in r.Variants) + { + 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} |")); + } + + 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 counts) + { + b.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 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("|---|---|---|---:|"); + foreach (var i in r.Instruments) + { + b.AppendLine(Text($"| {i.Symbol} | {i.First:yyyy-MM-dd} | {i.Last:yyyy-MM-dd} | {i.Bars} |")); + } + + b.AppendLine(); + } + + private static void Row(StringBuilder b, string label, string strategy, string benchmark) => + b.Append("| ").Append(label).Append(" | ").Append(strategy).Append(" | ").Append(benchmark).AppendLine(" |"); + + private static string Pct(double fraction, int decimals = 1) => + (fraction < 0 ? "−" : "") + Math.Abs(fraction * 100).ToString("N" + decimals.ToString(CultureInfo.InvariantCulture), It) + "%"; + + private static string Num(double value) => (value < 0 ? "−" : "") + Math.Abs(value).ToString("0.00", It); + + private static string Money(decimal value, string currency) => + (value < 0 ? "−" : "") + Math.Abs(value).ToString("#,0.00", It) + " " + (currency == "EUR" ? "€" : currency); + + private static string Text(FormattableString text) => text.ToString(It); +} diff --git a/src/Anubis/Backtest/Report.cs b/src/Anubis/Backtest/Report.cs index 01e4274..94201cc 100644 --- a/src/Anubis/Backtest/Report.cs +++ b/src/Anubis/Backtest/Report.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Globalization; using System.Text.Json; using Anubis.Data; using Anubis.Strategies; @@ -105,9 +106,10 @@ public static class TrialRunner ArgumentNullException.ThrowIfNull(data); ArgumentNullException.ThrowIfNull(prior); var watch = Stopwatch.StartNew(); - if (data.Sessions.Count < 30) + var sessions = data.Sessions.Count(d => d >= plan.Data.From && d <= plan.Data.To); + if (sessions < 30) { - throw new InvalidOperationException($"Dati insufficienti: {data.Sessions.Count} sedute, ne servono almeno 30."); + throw new InvalidOperationException($"Dati insufficienti: {sessions} sedute, ne servono almeno 30."); } var variants = ParameterGrid.Of(family, plan.Grid); @@ -116,7 +118,9 @@ public static class TrialRunner throw new InvalidOperationException("Nessuna combinazione valida nella griglia dei parametri."); } - var options = new BacktestOptions { InitialCapital = plan.InitialCapital }; + // The strategy goes through its correctives and the risk engine; buy and hold, the comparison, never does. + var plain = new BacktestOptions { InitialCapital = plan.InitialCapital, From = plan.Data.From, To = plan.Data.To }; + var options = StrategyPipeline.For(family.Id, data, plain, plan.ReferenceShare); var runs = new BacktestRun[variants.Count]; for (var i = 0; i < variants.Count; i++) { @@ -142,7 +146,7 @@ public static class TrialRunner costs.Add(new ReportCosts(multiplier, costed.NetResult, m.TotalReturn, m.Sharpe, m.MaxDrawdown, costed.Fees)); } - var benchmarkRun = BacktestEngine.Run(new BuyAndHold(data.Instruments.Count), data, options); + var benchmarkRun = BacktestEngine.Run(new BuyAndHold(data.Tradable.Count()), data, plain); var benchmark = BacktestMetrics.Of(benchmarkRun, data.PeriodsPerYear); cancellationToken.ThrowIfCancellationRequested(); @@ -201,7 +205,7 @@ public static class TrialRunner data.Fingerprint(), data.Currency, data.PeriodsPerYear, - data.Sessions.Count, + sessions, [.. data.Instruments.Select(i => new ReportInstrument(i.Symbol, i.Spec.Venue, i.Bars.Count > 0 ? i.Bars[0].Day : null, i.Bars.Count > 0 ? i.Bars[^1].Day : null, i.Bars.Count, i.Actions.Count, i.Source))], chosen.ToString(), @@ -241,11 +245,26 @@ public static class TrialRunner var result = new List { "I correttivi senza una storia ricostruibile (notizie, calendario economico, trimestrali, modello) non ricevono dati e non intervengono.", - "Il regime di mercato e i limiti di rischio arrivano con la Fase 5: in questo backtest ogni intenzione della strategia passa così com'è.", "Le decisioni si prendono sulla chiusura e si eseguono all'apertura della seduta dopo, con lo scostamento stimato: nessun inseguimento con ordini limite.", "Sharpe e volatilità sono calcolati senza tasso privo di rischio.", }; - if (plan.Data.Source == TrialSources.Research) + if (StrategyPipeline.IsBase(family.Id)) + { + var share = plan.ReferenceShare ?? StrategyPipeline.DefaultShare(family.Id) ?? 1m; + result.Add(string.Create(CultureInfo.GetCultureInfo("it-IT"), + $"Limiti di rischio e regime crypto applicati come dal vivo. La strategia è il {share * 100m:0.#}% del bot: il resto conta come liquidità ferma. Ogni chiusura vale come un giorno; se scatta l'interruttore, supponiamo che tu riparta dopo sette giorni. Età dei prezzi, prezzo dell'ordine e orologio esistono solo dal vivo.")); + } + else + { + result.Add("Strategia d'esempio: correttivi e limiti di rischio non si applicano, ogni intenzione passa così com'è."); + } + + if (plan.Data.Source == TrialSources.Research && plan.Data.Venue == EuroHistory.Venue) + { + result.Add("Prezzi dello storico Binance in USDT convertiti in euro con il cambio BCE del giorno, contando un USDT come un dollaro: è un'approssimazione delle coppie in euro di OKX. " + + "Su questo storico lo spread non si può misurare: l'universo sono le monete con più scambi, passo di prezzo e quantità minima sono stime, i costi sono quelli di OKX."); + } + else if (plan.Data.Source == TrialSources.Research) { result.Add("Prezzi dello storico Binance in USDT: passo di prezzo e quantità minima sono stime, i costi sono quelli di OKX."); } diff --git a/src/Anubis/Backtest/RiskStage.cs b/src/Anubis/Backtest/RiskStage.cs new file mode 100644 index 0000000..d5cdda9 --- /dev/null +++ b/src/Anubis/Backtest/RiskStage.cs @@ -0,0 +1,247 @@ +using System.Runtime.CompilerServices; +using Anubis.Data; +using Anubis.Risk; +using Anubis.Strategies; +using Anubis.Trading; + +namespace Anubis.Backtest; + +/// +/// The risk engine of SPEC 9 in the backtest of one strategy (SPEC 12.1): the same loss monitor and size rules as +/// live, measured on the strategy's closes. The strategy is one part of the bot; the rest is counted as cash that +/// does not move, so a loss of the strategy weighs on the world as its share does. Two choices of the backtest +/// (ADR 0011): every close is its own Italian day, and after the switch trips the user is assumed to restart a week +/// later, the high starting again from there. Price age, order price and clock exist only live. +/// +public sealed class BacktestRisk(RiskLimits? limits = null) : IIntentStage +{ + ///When the user is assumed to confirm the restart after the switch tripped. + public static readonly TimeSpan AssumedRestart = TimeSpan.FromDays(7); + + private readonly RiskLimits _limits = limits ?? RiskLimits.Default; + private readonly ConditionalWeakTable, Walker> _walkers = []; + + public string Name => "risk"; + + public RiskLimits Limits => _limits; + + /// Each close as a moment: noon UTC, inside its own Italian day. + public static DateTimeOffset At(DateOnly day) => new(day.ToDateTime(new TimeOnly(12, 0)), TimeSpan.Zero); + + public IReadOnlyListApply(StrategyContext context, IReadOnlyList intents) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(intents); + var walker = _walkers.GetValue(context.History, _ => new Walker(_limits)); + var (state, measures, other) = walker.Advance(context); + var now = At(context.Day); + if (state.Tripped) + { + // "Ferma tutto": nothing is bought or sold on the strategy's initiative; stops still follow it (SPEC 9.3). + return [.. intents.Select(i => i.TargetWeight is null ? i : (i with { TargetWeight = null, StopOffset = null }).Adjusted(RiskReasons.SwitchTripped))]; + } + + var blocked = RiskMonitor.EntriesBlocked(state, now); + var multiplier = RiskMonitor.Multiplier(state, measures, now, _limits); + var equity = context.Portfolio.Equity; + var invested = 0m; + var crypto = 0m; + foreach (var (symbol, h) in context.Portfolio.Holdings.Where(h => h.Value.Quantity > 0m)) + { + var value = h.Quantity * BookWeights.Price(context, symbol); + invested += value; + if (context.Spec(symbol)?.AssetClass == AssetClasses.Crypto) + { + crypto += value; + } + } + + var result = new List (intents.Count); + foreach (var intent in intents) + { + if (intent.TargetWeight is not { } target || equity <= 0m) + { + result.Add(intent); + continue; + } + + var current = BookWeights.Current(context, intent.Symbol); + if (target <= current) + { + result.Add(intent); + continue; + } + + if (blocked) + { + result.Add(BookWeights.Reduce(context, intent, 0m, RiskReasons.DailyLossBlock)); + continue; + } + + var price = BookWeights.Price(context, intent.Symbol); + var holding = context.Portfolio.Of(intent.Symbol); + var held = holding?.Quantity ?? 0m; + var stop = intent.Stop ?? holding?.Stop ?? (intent.StopOffset is { } offset ? price - offset : null); + var isCrypto = context.Spec(intent.Symbol)?.AssetClass == AssetClasses.Crypto; + var wanted = (target * equity / price) - held; + var size = RiskRules.SizePurchase(new PurchaseRequest + { + Price = price, + Held = held, + Wanted = wanted, + Stop = stop, + Multiplier = multiplier, + WorldEquity = equity + other, + WorldInvested = invested, + Reference = context.ReferenceEquity, + IsCrypto = isCrypto, + CryptoValue = crypto, + }, _limits); + var bought = size.Reduced ? size.Quantity : wanted; + invested += bought * price; + crypto += isCrypto ? bought * price : 0m; + if (!size.Reduced) + { + result.Add(intent); + continue; + } + + var weight = Math.Round((held + size.Quantity) * price / equity, 6, MidpointRounding.ToZero); + var adjusted = intent; + foreach (var reason in size.Reasons) + { + adjusted = adjusted.Adjusted(reason); + } + + result.Add(weight > current + ? adjusted with { TargetWeight = weight } + : held > 0m ? adjusted with { TargetWeight = null } : adjusted with { TargetWeight = null, Stop = null, StopOffset = null }); + } + + // A position heavier than the threshold comes back to it at the first chance (SPEC 9.2). + foreach (var (symbol, h) in context.Portfolio.Holdings.Where(h => h.Value.Quantity > 0m)) + { + var price = BookWeights.Price(context, symbol); + if (RiskRules.Excess(h.Quantity, price, context.ReferenceEquity, _limits) <= 0m) + { + continue; + } + + var most = Math.Round(_limits.MaxPosition * context.ReferenceEquity / equity, 6, MidpointRounding.ToZero); + var index = result.FindLastIndex(i => i.Symbol == symbol); + if (index >= 0 && result[index].TargetWeight is { } w && w <= most) + { + continue; + } + + if (index >= 0) + { + result[index] = (result[index] with { TargetWeight = most }).Adjusted(RiskReasons.PositionLimit); + } + else + { + result.Add(new Intent(symbol, most, RiskReasons.PositionLimit) { Adjustments = [RiskReasons.PositionLimit] }); + } + } + + return result; + } + + /// The loss monitor walked along one run's closes, one step for each new close. + private sealed class Walker(RiskLimits limits) + { + private readonly Lock _lock = new(); + private readonly List_points = []; + private RiskMonitorState _state = RiskMonitorState.Initial; + private RiskMeasures _measures = RiskMeasures.None; + private decimal _peak; + private decimal? _other; + + public (RiskMonitorState State, RiskMeasures Measures, decimal Other) Advance(StrategyContext context) + { + lock (_lock) + { + var history = context.History; + // The rest of the bot, as cash that does not move: the strategy's first equity times (1 / share − 1). + _other ??= history.Count > 0 && context.Portfolio.Equity > 0m + ? Math.Max(0m, history[0].Equity * ((context.ReferenceEquity / context.Portfolio.Equity) - 1m)) + : 0m; + for (var i = _points.Count; i < history.Count; i++) + { + var at = At(history[i].Day); + var index = history[i].Equity + _other.Value; + if (_state.Tripped && _state.TrippedAt is { } tripped && at >= tripped + AssumedRestart) + { + _state = RiskMonitor.Restart(_state, at); + _peak = 0m; + } + + _points.Add(new IndexPoint(at, index)); + _peak = Math.Max(_peak, index); + var dayBase = i > 0 ? _points[i - 1].Index : index; + var weekBase = _points[WeekBase(at - TimeSpan.FromDays(7))].Index; + _measures = new RiskMeasures(RiskMeasures.Change(index, dayBase), RiskMeasures.Change(index, weekBase), RiskMeasures.Change(index, _peak)); + _state = RiskMonitor.Step(_state, _measures, at, limits).State; + } + + return (_state, _measures, _other.Value); + } + } + + private int WeekBase(DateTimeOffset at) + { + int lo = 0, hi = _points.Count - 1, found = 0; + while (lo <= hi) + { + var mid = (lo + hi) / 2; + if (_points[mid].At <= at) + { + found = mid; + lo = mid + 1; + } + else + { + hi = mid - 1; + } + } + + return found; + } + } +} + +/// +/// The full path of a decision in the backtest (SPEC 5.2): the base strategies go through their correctives and the +/// risk engine, with the share of the bot each one has by default (SPEC 8.6: 40%, 45% and 15% with the example +/// capital). The examples of the laboratory and the buy-and-hold comparison go through as they are. +/// +public static class StrategyPipeline +{ + public static decimal? DefaultShare(string strategy) => strategy switch + { + StrategyNames.CryptoTrend => 0.40m, + StrategyNames.EquityMomentum => 0.45m, + StrategyNames.EquityMeanrev => 0.15m, + _ => null, + }; + + public static bool IsBase(string strategy) => DefaultShare(strategy) is not null; + + public static BacktestOptions For(string strategy, BacktestDataset data, BacktestOptions options, decimal? share = null) + { + ArgumentNullException.ThrowIfNull(data); + ArgumentNullException.ThrowIfNull(options); + if (!IsBase(strategy)) + { + return options; + } + + IReadOnlyListcorrectives = []; + if (strategy == StrategyNames.CryptoTrend && data.Tradable.FirstOrDefault(i => Symbols.BaseOf(i.Spec) == "BTC") is { } bitcoin) + { + correctives = [new CryptoRegimeStage(bitcoin.Symbol)]; + } + + return options with { Correctives = correctives, Risk = new BacktestRisk(), ReferenceShare = share ?? options.ReferenceShare ?? DefaultShare(strategy) }; + } +} diff --git a/src/Anubis/Backtest/Trials.cs b/src/Anubis/Backtest/Trials.cs index 35260c8..96cd14a 100644 --- a/src/Anubis/Backtest/Trials.cs +++ b/src/Anubis/Backtest/Trials.cs @@ -17,8 +17,19 @@ public static class TrialSources public const string Research = "research"; } -/// The data a trial reads: one venue, a few instruments, a period (both days included). -public sealed record TrialData(string Source, string Venue, IReadOnlyListSymbols, DateOnly From, DateOnly To); +/// +/// The data a trial reads: one venue, a few instruments, a period (both days included). The bars of the +/// +public sealed record TrialData(string Source, string Venue, IReadOnlyListbefore are read too, only so the indicators and the listing age are ready on +/// the first day: the simulation, the measures and buy and hold start at . +/// Symbols, DateOnly From, DateOnly To) +{ + /// Calendar days of history before the start: a year of 252 sessions, a 360-day lookback, 400 days of listing. + public const int WarmupDays = 450; + + ///The first day read from the history. + public DateOnly HistoryStart() => From.AddDays(-WarmupDays); +} ////// The thresholds of SPEC 12.2, fixed in the plan before the trial runs: changing them after seeing the results needs @@ -51,6 +62,12 @@ public sealed record TrialPlan( string Engine, DateTimeOffset WrittenAt) { + /// + /// The strategy's share of the bot (SPEC 9.2): the reference equity of the backtest is its capital divided by it. + /// Null for the examples, which are not part of the bot. + /// + public decimal? ReferenceShare { get; init; } + public static readonly JsonSerializerOptions Json = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, diff --git a/src/Anubis/Core/Settings.cs b/src/Anubis/Core/Settings.cs index fc66c67..47ddac9 100644 --- a/src/Anubis/Core/Settings.cs +++ b/src/Anubis/Core/Settings.cs @@ -41,7 +41,8 @@ public sealed class SettingsStore(Database db, IClock clock, EventBus bus, IRead public static readonly SettingDefinition CentralBankMeetings = new("calendar.central_banks", "Riunioni di Fed e BCE", Data.CentralBanks.DefaultList, Check: Data.CentralBanks.Check); - public static readonly IReadOnlyListAll = [Theme, Currency, BotState, CentralBankMeetings]; + public static readonly IReadOnlyList All = + [Theme, Currency, BotState, CentralBankMeetings, .. Risk.RiskSettings.All, Risk.Scenarios.Setting]; private readonly IReadOnlyDictionary _overrides = overrides ?? new Dictionary (); diff --git a/src/Anubis/Db/Migrations/0005_risk.sql b/src/Anubis/Db/Migrations/0005_risk.sql new file mode 100644 index 0000000..0419d6f --- /dev/null +++ b/src/Anubis/Db/Migrations/0005_risk.sql @@ -0,0 +1,49 @@ +-- Phase 5 schema (SPEC 5.2, 9, 12.3, 12.4, ADR 0011): the record of every stage of a decision, the state of the +-- risk engine for each world, and what a strategy needs to reach real money and to leave it. + +-- One row for each stage a decision goes through (SPEC 5.2): strategy, correctives, sizing, risk, order. Reason +-- codes and the numbers used, never free text: the diary and the "why" card are written from these rows with fixed +-- templates. decision_id groups the rows of one decision. +CREATE TABLE decisions ( + id {uuid} PRIMARY KEY, + decision_id {uuid} NOT NULL, + strategy TEXT NOT NULL, + account_id {uuid}, + symbol TEXT, + stage TEXT NOT NULL, + outcome TEXT NOT NULL, + reasons {json} NOT NULL, + data {json}, + created_at {timestamp} NOT NULL +){strict}; + +CREATE INDEX decisions_decision ON decisions (decision_id); +CREATE INDEX decisions_strategy ON decisions (strategy, created_at); + +-- What the risk engine remembers for each world (SPEC 9.2, 9.3): blocks with their end, the moment the high is +-- measured from, the switch tripped by a limit and the warnings already sent. One row per world. +CREATE TABLE risk_state ( + id {uuid} PRIMARY KEY, + world TEXT NOT NULL UNIQUE, + state {json} NOT NULL, + created_at {timestamp} NOT NULL, + updated_at {timestamp} NOT NULL +){strict}; + +-- Risk events belong to a world (SPEC 9.2: a limit stops only the world where it was crossed). +ALTER TABLE risk_events ADD COLUMN world TEXT; + +CREATE INDEX risk_events_time ON risk_events (occurred_at); + +-- Stages (SPEC 12.3, 12.4, 7.1). account_id stays the account of the simulation (internal simulator or demo); +-- live_account_id is the real account, once the strategy has one. live_confirmed_at is set only by the procedure +-- of 12.4 and cleared by a revocation or a demotion; exit_only keeps a demoted strategy managing its real +-- positions down to zero. stage_since and stage_reason say since when and why the strategy is where it is; +-- qualification is the backtest outcome it qualified with, which the requirements and demotions compare against. +ALTER TABLE strategy_state ADD COLUMN live_account_id {uuid}; +ALTER TABLE strategy_state ADD COLUMN live_confirmed_at {timestamp}; +ALTER TABLE strategy_state ADD COLUMN live_confirmed_by TEXT; +ALTER TABLE strategy_state ADD COLUMN exit_only {bool}; +ALTER TABLE strategy_state ADD COLUMN stage_since {timestamp}; +ALTER TABLE strategy_state ADD COLUMN stage_reason TEXT; +ALTER TABLE strategy_state ADD COLUMN qualification {json}; diff --git a/src/Anubis/Demo/DemoMode.cs b/src/Anubis/Demo/DemoMode.cs index 8f8494d..ae142fb 100644 --- a/src/Anubis/Demo/DemoMode.cs +++ b/src/Anubis/Demo/DemoMode.cs @@ -120,10 +120,25 @@ public static class DemoMode ["Mean reversion"] = ("equity_meanrev", alpaca, 1740.15m, 1236.71m, 0.25m), }; var currencyOf = new Dictionary { [okx] = "EUR", [alpaca] = "USD" }; + // F.4: 58 days of 60 in simulation, after a passed backtest (an example: the real outcomes are in docs/backtests). foreach (var (name, account, capital, _, share) in strategies.Values) { - await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, share, state, created_at, updated_at) VALUES (@id, @n, @a, 'simulation', @c, @sh, @st, @t, @t)", - cancellationToken, ("id", ids.Next()), ("n", name), ("a", account), ("c", capital), ("sh", share), ("st", new DbJson("{\"day\":58,\"of\":60}")), ("t", now)) + var example = new Trading.Qualification + { + Passed = true, + Verdict = "Superato (dato di esempio).", + Report = "docs/backtests/" + name + ".md", + MaxDrawdown = 0.18m, + ExpectedSlippageBp = 8m, + RoundTripCost = 0.0056m, + ExpectedPathP5 = [.. Enumerable.Range(1, 365).Select(d => Math.Round(-0.012 * Math.Sqrt(d), 4))], + }; + await s.ExecuteAsync( + "INSERT INTO strategy_state (id, strategy, account_id, stage, stage_since, stage_reason, qualification, capital, share, state, created_at, updated_at) " + + "VALUES (@id, @n, @a, 'simulation', @since, 'user', @q, @c, @sh, @st, @t, @t)", + cancellationToken, ("id", ids.Next()), ("n", name), ("a", account), ("since", now.AddDays(-58)), + ("q", new DbJson(JsonSerializer.Serialize(example, Trading.Qualification.Json))), ("c", capital), ("sh", share), + ("st", new DbJson("{\"day\":58,\"of\":60}")), ("t", now)) .ConfigureAwait(false); } @@ -177,20 +192,22 @@ public static class DemoMode [ ("account", okx, null, 4000m, 231.60m), ("account", alpaca, null, 6000m, 180.86m), - ("strategy", null, "crypto_trend", 4000m, 231.60m), - ("strategy", null, "equity_momentum", 4500m, 169.50m), - ("strategy", null, "equity_meanrev", 1500m, 11.36m), + ("strategy", okx, "crypto_trend", 4000m, 231.60m), + ("strategy", alpaca, "equity_momentum", 4500m, 169.50m), + ("strategy", alpaca, "equity_meanrev", 1500m, 11.36m), ]; foreach (var (day, equity, benchmark, drawdown) in daily) { var at = day == DateOnly.FromDateTime(Now.DateTime) ? now : new DateTimeOffset(day.ToDateTime(new TimeOnly(22, 0)), rome.GetUtcOffset(day.ToDateTime(new TimeOnly(22, 0)))); - await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, world, currency, equity, benchmark, drawdown_pct, created_at) VALUES (@id, @at, 'total', 'simulated', 'EUR', @e, @b, @d, @t)", - cancellationToken, ("id", ids.Next()), ("at", at), ("e", equity), ("b", benchmark), ("d", drawdown), ("t", now)).ConfigureAwait(false); + await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, world, currency, equity, benchmark, drawdown_pct, twr_index, created_at) VALUES (@id, @at, 'total', 'simulated', 'EUR', @e, @b, @d, @x, @t)", + cancellationToken, ("id", ids.Next()), ("at", at), ("e", equity), ("b", benchmark), ("d", drawdown), ("x", Math.Round(equity / 10000m, 6)), ("t", now)).ConfigureAwait(false); foreach (var (scope, account, strategy, start, result) in series) { var value = Math.Round(start + (equity - 10000m) * result / total, 2, MidpointRounding.AwayFromZero); - await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, world, currency, account_id, strategy, equity, created_at) VALUES (@id, @at, @sc, 'simulated', 'EUR', @a, @st, @e, @t)", - cancellationToken, ("id", ids.Next()), ("at", at), ("sc", scope), ("a", account), ("st", strategy), ("e", value), ("t", now)).ConfigureAwait(false); + // Without deposits along the way the index is the value over the start. + await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, world, currency, account_id, strategy, equity, twr_index, created_at) VALUES (@id, @at, @sc, 'simulated', 'EUR', @a, @st, @e, @x, @t)", + cancellationToken, ("id", ids.Next()), ("at", at), ("sc", scope), ("a", account), ("st", strategy), ("e", value), ("x", Math.Round(value / start, 6)), ("t", now)) + .ConfigureAwait(false); } } @@ -269,6 +286,50 @@ public static class DemoMode "VALUES (@id, @a, @i, @s, 'closed', @o, @c, @q, @b, @q, @sv, @f, @r, @e, @t, @t)", cancellationToken, ("id", ids.Next()), ("a", account), ("i", instrument), ("s", strategy), ("o", closed.AddDays(-5)), ("c", closed), ("q", quantity), ("b", bought), ("sv", bought + realized + fee), ("f", fee), ("r", realized), ("e", realized >= 0m ? "signal" : "stop"), ("t", now)).ConfigureAwait(false); + await SeedWhyAsync(s, ids, account, instrument, strategy, symbol, quantity, bought, bought + realized + fee, closed.AddDays(-5), closed, realized < 0m, now, cancellationToken) + .ConfigureAwait(false); + } + } + + // F.6: the decisions behind each trade, so its "why" card has lines: the strategy's reason, correctives and risk on + // the purchase; the strategy's exit on a sale it decided, or the protective stop that sold at a loss. + private static async Task SeedWhyAsync(DbSession s, IdSource ids, Guid account, Guid instrument, string strategy, string symbol, decimal quantity, decimal bought, + decimal sold, DateTimeOffset opened, DateTimeOffset closed, bool stopped, DateTimeOffset now, CancellationToken cancellationToken) + { + var (entry, exit) = strategy switch + { + "crypto_trend" => ("trend_entry", "trend_exit"), + "equity_momentum" => ("momentum_entry", "momentum_exit_rank"), + _ => ("meanrev_entry", "meanrev_exit_average"), + }; + + async Task DecideAsync(Guid decision, string stage, string outcome, string[] reasons, DateTimeOffset at) => + await s.ExecuteAsync( + "INSERT INTO decisions (id, decision_id, strategy, account_id, symbol, stage, outcome, reasons, data, created_at) VALUES (@id, @d, @s, @a, @sym, @st, @o, @r, NULL, @t)", + cancellationToken, ("id", ids.Next()), ("d", decision), ("s", strategy), ("a", account), ("sym", symbol), ("st", stage), ("o", outcome), + ("r", new DbJson(JsonSerializer.Serialize(reasons))), ("t", at)).ConfigureAwait(false); + + async Task ExecuteAsync(string side, string purpose, Guid decision, decimal reference, DateTimeOffset at) => + await s.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, @side, @p, @q, @q, @k, 1, 0, @r, @st, @at, @t, @t)", + cancellationToken, ("id", ids.Next()), ("a", account), ("i", instrument), ("s", strategy), ("side", side), ("p", purpose), ("q", quantity), + ("k", Trading.ClientOrderIds.Key(decision)), ("r", Math.Round(reference, 6)), ("st", Trading.ExecutionStates.Done), ("at", at), ("t", now)).ConfigureAwait(false); + + var buy = ids.Next(); + await DecideAsync(buy, Trading.DecisionStages.Strategy, Trading.DecisionOutcomes.Proposed, [entry], opened.AddMinutes(-1)).ConfigureAwait(false); + await DecideAsync(buy, Trading.DecisionStages.Correctives, Trading.DecisionOutcomes.Passed, [], opened.AddMinutes(-1)).ConfigureAwait(false); + await DecideAsync(buy, Trading.DecisionStages.Risk, Trading.DecisionOutcomes.Passed, [], opened.AddMinutes(-1)).ConfigureAwait(false); + await ExecuteAsync("buy", "entry", buy, bought / quantity / 1.0002m, opened).ConfigureAwait(false); + if (stopped) + { + await ExecuteAsync("sell", "protective", ids.Next(), sold / quantity * 1.0003m, closed).ConfigureAwait(false); + } + else + { + var sale = ids.Next(); + await DecideAsync(sale, Trading.DecisionStages.Strategy, Trading.DecisionOutcomes.Proposed, [exit], closed.AddMinutes(-1)).ConfigureAwait(false); + await ExecuteAsync("sell", "exit", sale, sold / quantity * 1.0001m, closed).ConfigureAwait(false); } } diff --git a/src/Anubis/Risk/RiskLimits.cs b/src/Anubis/Risk/RiskLimits.cs new file mode 100644 index 0000000..d58ece4 --- /dev/null +++ b/src/Anubis/Risk/RiskLimits.cs @@ -0,0 +1,151 @@ +using System.Globalization; +using Anubis.Core; + +namespace Anubis.Risk; + +/// +/// The limits of SPEC 9.2 with their default values. Only the user changes them, from the settings; a change that +/// raises a limit while a strategy is in the real account needs the procedure of SPEC 12.4. +/// +public sealed record RiskLimits +{ + ///Loss in a day (Italian midnight to now): no new entries for 24 hours. + public decimal DailyLoss { get; init; } = 0.02m; + + ///Loss over the last seven days: risk halved for seven days. + public decimal WeeklyLoss { get; init; } = 0.05m; + + ///Fall from the high at which the risk is halved. + public decimal DrawdownHalf { get; init; } = 0.10m; + + ///Fall from the high at which the emergency switch trips and the bot waits for the user. + public decimal DrawdownStop { get; init; } = 0.15m; + + ///Capital in positions over the world's equity: no other purchase beyond it. + public decimal MaxInvested { get; init; } = 1m; + + ///One position over the reference equity: brought back to the threshold at the first chance. + public decimal MaxPosition { get; init; } = 0.20m; + + ///Crypto over the reference equity: no new crypto purchases beyond it. + public decimal MaxCrypto { get; init; } = 0.40m; + + ///Loss if the stop of a whole position triggered, over the reference equity: the purchase is shrunk. + public decimal MaxTradeRisk { get; init; } = 0.01m; + + ///Purchases and sales really sent to one account in a minute: beyond, the bot stops and warns. + public int OrdersPerMinute { get; init; } = 10; + + ///Age of the last price: no new entry on the instrument beyond it. + public TimeSpan MaxPriceAge { get; init; } = TimeSpan.FromSeconds(60); + + ///Distance of a purchase's limit from the last valid price: refused beyond it. + public decimal MaxPriceGap { get; init; } = 0.01m; + + ///Gap between the bot's clock and the broker's: no new entries beyond it. + public TimeSpan MaxClockSkew { get; init; } = TimeSpan.FromSeconds(2); + + ///Share of a threshold at which a warning starts, without any block (SPEC 9.2). + public const decimal WarningShare = 0.8m; + + public static TimeSpan DailyBlock { get; } = TimeSpan.FromHours(24); + + public static TimeSpan WeeklyHalving { get; } = TimeSpan.FromDays(7); + + public static RiskLimits Default { get; } = new(); + + ///True when + public bool RaisedBy(RiskLimits next) + { + ArgumentNullException.ThrowIfNull(next); + return next.DailyLoss > DailyLoss || next.WeeklyLoss > WeeklyLoss || next.DrawdownHalf > DrawdownHalf || next.DrawdownStop > DrawdownStop + || next.MaxInvested > MaxInvested || next.MaxPosition > MaxPosition || next.MaxCrypto > MaxCrypto || next.MaxTradeRisk > MaxTradeRisk + || next.OrdersPerMinute > OrdersPerMinute || next.MaxPriceAge > MaxPriceAge || next.MaxPriceGap > MaxPriceGap || next.MaxClockSkew > MaxClockSkew; + } +} + +///allows more risk than this on at least one limit. +/// The limits as settings (SPEC 13.5): percentages and counts written as the user reads them ("2" is 2%). Every +/// change goes to the change log like any other setting. +/// +public static class RiskSettings +{ + private static readonly CultureInfo Invariant = CultureInfo.InvariantCulture; + + public static readonly SettingDefinition DailyLoss = Percent("risk.daily_loss", "Perdita in un giorno (%)", RiskLimits.Default.DailyLoss, 0.5m, 10m); + public static readonly SettingDefinition WeeklyLoss = Percent("risk.weekly_loss", "Perdita in una settimana (%)", RiskLimits.Default.WeeklyLoss, 1m, 20m); + public static readonly SettingDefinition DrawdownHalf = Percent("risk.drawdown_half", "Calo dal massimo: rischio dimezzato (%)", RiskLimits.Default.DrawdownHalf, 2m, 30m); + public static readonly SettingDefinition DrawdownStop = Percent("risk.drawdown_stop", "Calo dal massimo: interruttore (%)", RiskLimits.Default.DrawdownStop, 3m, 40m); + public static readonly SettingDefinition MaxInvested = Percent("risk.max_invested", "Capitale investito (%)", RiskLimits.Default.MaxInvested, 10m, 100m); + public static readonly SettingDefinition MaxPosition = Percent("risk.max_position", "Peso di una sola posizione (%)", RiskLimits.Default.MaxPosition, 1m, 50m); + public static readonly SettingDefinition MaxCrypto = Percent("risk.max_crypto", "Crypto sul totale (%)", RiskLimits.Default.MaxCrypto, 0m, 100m); + public static readonly SettingDefinition MaxTradeRisk = Percent("risk.max_trade_risk", "Rischio di una singola operazione (%)", RiskLimits.Default.MaxTradeRisk, 0.1m, 5m); + + public static readonly SettingDefinition OrdersPerMinute = new("risk.orders_per_minute", "Ordini al minuto", "10", Check: v => Whole(v, 1, 60)); + + public static readonly SettingDefinition MaxPriceAge = new("risk.price_age", "Età dei prezzi (secondi)", "60", Check: v => Whole(v, 5, 600)); + + public static readonly SettingDefinition MaxPriceGap = Percent("risk.price_gap", "Prezzo dell'ordine: distanza dall'ultimo prezzo (%)", RiskLimits.Default.MaxPriceGap, 0.1m, 5m); + + public static readonly SettingDefinition MaxClockSkew = new("risk.clock_skew", "Scarto dell'orologio (secondi)", "2", Check: v => Whole(v, 1, 30)); + + ///Day-trade protection (SPEC 9.2, + public static readonly SettingDefinition PdtGuard = new("risk.pdt_guard", "Protezione day trade", "off", ["off", "on"]); + + public static readonly IReadOnlyListpdt_guard ): off by default.Limits = + [DailyLoss, WeeklyLoss, DrawdownHalf, DrawdownStop, MaxInvested, MaxPosition, MaxCrypto, MaxTradeRisk, OrdersPerMinute, MaxPriceAge, MaxPriceGap, MaxClockSkew]; + + public static readonly IReadOnlyList All = [.. Limits, PdtGuard]; + + /// The limits from settings: + public static RiskLimits From(Funcreads a key and returns its text. value) + { + ArgumentNullException.ThrowIfNull(value); + decimal P(SettingDefinition d) => decimal.Parse(value(d.Key), Invariant) / 100m; + int W(SettingDefinition d) => int.Parse(value(d.Key), Invariant); + return new RiskLimits + { + DailyLoss = P(DailyLoss), + WeeklyLoss = P(WeeklyLoss), + DrawdownHalf = P(DrawdownHalf), + DrawdownStop = P(DrawdownStop), + MaxInvested = P(MaxInvested), + MaxPosition = P(MaxPosition), + MaxCrypto = P(MaxCrypto), + MaxTradeRisk = P(MaxTradeRisk), + OrdersPerMinute = W(OrdersPerMinute), + MaxPriceAge = TimeSpan.FromSeconds(W(MaxPriceAge)), + MaxPriceGap = P(MaxPriceGap), + MaxClockSkew = TimeSpan.FromSeconds(W(MaxClockSkew)), + }; + } + + public static async Task LoadAsync(SettingsStore settings, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(settings); + var values = new Dictionary (StringComparer.Ordinal); + foreach (var definition in Limits) + { + values[definition.Key] = (await settings.GetAsync(definition.Key, cancellationToken).ConfigureAwait(false)).Value; + } + + return From(k => values[k]); + } + + public static async Task PdtGuardAsync(SettingsStore settings, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(settings); + return (await settings.GetAsync(PdtGuard.Key, cancellationToken).ConfigureAwait(false)).Value == "on"; + } + + private static SettingDefinition Percent(string key, string label, decimal fraction, decimal min, decimal max) => + new(key, label, (fraction * 100m).ToString("0.##", Invariant), Check: v => Number(v, min, max)); + + private static string? Number(string text, decimal min, decimal max) => + decimal.TryParse(text, NumberStyles.Number, Invariant, out var value) && value >= min && value <= max + ? null + : string.Create(CultureInfo.GetCultureInfo("it-IT"), $"Serve un numero tra {min} e {max}."); + + private static string? Whole(string text, int min, int max) => + int.TryParse(text, NumberStyles.None, Invariant, out var value) && value >= min && value <= max ? null : $"Serve un numero intero tra {min} e {max}."; +} diff --git a/src/Anubis/Risk/RiskMonitor.cs b/src/Anubis/Risk/RiskMonitor.cs new file mode 100644 index 0000000..b95a2a3 --- /dev/null +++ b/src/Anubis/Risk/RiskMonitor.cs @@ -0,0 +1,259 @@ +using System.Globalization; +using Anubis.Data; + +namespace Anubis.Risk; + +/// A point of a world's time-weighted index: deposits and withdrawals never look like gains or losses (SPEC 7.5). +public sealed record IndexPoint(DateTimeOffset At, decimal Index); + +///The three measures of SPEC 9.2, as changes: −0.03 is a loss of 3%. +public sealed record RiskMeasures(decimal DayChange, decimal WeekChange, decimal Drawdown) +{ + public static RiskMeasures None { get; } = new(0m, 0m, 0m); + + ///+ /// The measures at + public static RiskMeasures From(IReadOnlyList: the day starts at Italian midnight, the week is the last seven days, the + /// high is the highest point since (the start, or the last confirmed restart). + /// series, DateTimeOffset now, DateTimeOffset? peakFrom, decimal? knownPeak = null) + { + ArgumentNullException.ThrowIfNull(series); + var last = LastAtOrBefore(series, now); + if (last < 0) + { + return None; + } + + var current = series[last].Index; + var midnight = RiskMonitor.ItalianMidnight(now); + var dayIndex = LastAtOrBefore(series, midnight.AddTicks(-1)); + var dayBase = series[Math.Max(dayIndex, 0)].Index; + var weekIndex = LastAtOrBefore(series, now - TimeSpan.FromDays(7)); + var weekBase = series[Math.Max(weekIndex, 0)].Index; + var peak = Math.Max(current, knownPeak ?? current); + for (var i = last; i >= 0 && (peakFrom is null || series[i].At >= peakFrom); i--) + { + peak = Math.Max(peak, series[i].Index); + } + + return new RiskMeasures(Change(current, dayBase), Change(current, weekBase), Change(current, peak)) { Index = current, Peak = peak }; + } + + /// The index the measures were taken on. + public decimal? Index { get; init; } + + ///The high the fall is measured from: kept by the engine between readings, so the series can be short. + public decimal? Peak { get; init; } + + public static decimal Change(decimal current, decimal reference) => reference <= 0m ? 0m : (current / reference) - 1m; + + private static int LastAtOrBefore(IReadOnlyListseries, DateTimeOffset at) + { + int lo = 0, hi = series.Count - 1, found = -1; + while (lo <= hi) + { + var mid = (lo + hi) / 2; + if (series[mid].At <= at) + { + found = mid; + lo = mid + 1; + } + else + { + hi = mid - 1; + } + } + + return found; + } +} + +/// +/// What the risk engine remembers about a world (SPEC 9.2, 9.3): the 24-hour block after a day's loss, the seven +/// days of halved risk after a week's loss, the moment the high is measured from, the switch tripped by the fall +/// from the high, and the warnings already sent (one for each crossing). +/// +public sealed record RiskMonitorState +{ + public DateTimeOffset? DailyBlockUntil { get; init; } + + public DateTimeOffset? WeeklyHalvingUntil { get; init; } + + ///The high counts points from this moment: the start, or the last confirmed restart after a trip. + public DateTimeOffset? PeakFrom { get; init; } + + ///The highest index seen since + public decimal? Peak { get; init; } + + ///. The fall from the high reached the stop threshold: entries and sales of the strategies stop until the user confirms. + public bool Tripped { get; init; } + + public DateTimeOffset? TrippedAt { get; init; } + + ///Measures beyond 80% of their threshold, already warned about; a measure leaves the list when it comes back. + public IReadOnlyListWarned { get; init; } = []; + + public static RiskMonitorState Initial { get; } = new(); +} + +/// Something the monitor saw: a limit crossed, a warning at 80% of a threshold. +public sealed record RiskAlert(string Kind, string Severity, string Message, decimal Value, decimal Threshold); + +public static class RiskAlertKinds +{ + public const string DailyLoss = "daily_loss"; + public const string WeeklyLoss = "weekly_loss"; + public const string DrawdownHalf = "drawdown_half"; + public const string DrawdownStop = "drawdown_stop"; + public const string Warning = "warning"; +} + +public static class RiskSeverities +{ + public const string Info = "info"; + public const string Warning = "warning"; + public const string High = "high"; + public const string Critical = "critical"; +} + +public sealed record RiskReading(RiskMonitorState State, RiskMeasures Measures, IReadOnlyListAlerts); + +/// +/// The loss limits of SPEC 9.2 as a pure state machine: the same steps run in the backtest, on the closes of one +/// strategy, and live, on every photograph of a world's equity. It never raises the risk: the multiplier it gives is +/// one or less, and lower the larger the losses. +/// +public static class RiskMonitor +{ + private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT"); + + ///Midnight in Italy of the day + public static DateTimeOffset ItalianMidnight(DateTimeOffset at) + { + var local = TimeZoneInfo.ConvertTime(at, Zones.Rome); + var midnight = local.Date; + return new DateTimeOffset(midnight, Zones.Rome.GetUtcOffset(midnight)); + } + + public static RiskReading Step(RiskMonitorState state, RiskMeasures m, DateTimeOffset now, RiskLimits limits) + { + ArgumentNullException.ThrowIfNull(state); + ArgumentNullException.ThrowIfNull(m); + ArgumentNullException.ThrowIfNull(limits); + var alerts = new Listfalls on, as a UTC moment. (); + var next = state; + if (m.DayChange <= -limits.DailyLoss && !(state.DailyBlockUntil > now)) + { + next = next with { DailyBlockUntil = now + RiskLimits.DailyBlock }; + alerts.Add(new(RiskAlertKinds.DailyLoss, RiskSeverities.High, + $"Perdita di oggi {Percent(m.DayChange)}, oltre la soglia del {Percent(-limits.DailyLoss)}: niente nuovi ingressi per 24 ore.", m.DayChange, -limits.DailyLoss)); + } + + if (m.WeekChange <= -limits.WeeklyLoss && !(state.WeeklyHalvingUntil > now)) + { + next = next with { WeeklyHalvingUntil = now + RiskLimits.WeeklyHalving }; + alerts.Add(new(RiskAlertKinds.WeeklyLoss, RiskSeverities.High, + $"Perdita degli ultimi sette giorni {Percent(m.WeekChange)}, oltre la soglia del {Percent(-limits.WeeklyLoss)}: rischio dimezzato per sette giorni.", + m.WeekChange, -limits.WeeklyLoss)); + } + + if (!state.Tripped && m.Drawdown <= -limits.DrawdownStop) + { + next = next with { Tripped = true, TrippedAt = now }; + alerts.Add(new(RiskAlertKinds.DrawdownStop, RiskSeverities.Critical, + $"Calo dal massimo {Percent(m.Drawdown)}, oltre la soglia del {Percent(-limits.DrawdownStop)}: interruttore scattato, aspetto la tua conferma per ripartire.", + m.Drawdown, -limits.DrawdownStop)); + } + + // Warnings at 80% of a threshold: one for each crossing, again only after the measure has come back. + var warned = new List (state.Warned); + void Watch(string key, decimal value, decimal threshold, string what) + { + var near = value <= -threshold * RiskLimits.WarningShare; + if (near && !warned.Contains(key)) + { + warned.Add(key); + alerts.Add(new(RiskAlertKinds.Warning, RiskSeverities.Warning, + $"{what} {Percent(value)}: oltre l'80% della soglia del {Percent(-threshold)}. Nessun blocco per ora.", value, -threshold)); + } + else if (!near) + { + warned.Remove(key); + } + } + + Watch("day", m.DayChange, limits.DailyLoss, "Perdita di oggi"); + Watch("week", m.WeekChange, limits.WeeklyLoss, "Perdita degli ultimi sette giorni"); + Watch("drawdown_half", m.Drawdown, limits.DrawdownHalf, "Calo dal massimo"); + Watch("drawdown_stop", m.Drawdown, limits.DrawdownStop, "Calo dal massimo"); + + // The halving for the fall from the high has no duration: it lasts while the fall does, and is said once. + const string halvingKey = "drawdown_half:on"; + if (m.Drawdown <= -limits.DrawdownHalf) + { + if (!warned.Contains(halvingKey)) + { + warned.Add(halvingKey); + alerts.Add(new(RiskAlertKinds.DrawdownHalf, RiskSeverities.High, + $"Calo dal massimo {Percent(m.Drawdown)}, oltre la soglia del {Percent(-limits.DrawdownHalf)}: rischio dimezzato finché non rientra.", + m.Drawdown, -limits.DrawdownHalf)); + } + } + else + { + warned.Remove(halvingKey); + } + + next = next with { Warned = warned, Peak = m.Peak is { } p ? Math.Max(p, state.Peak ?? p) : state.Peak }; + return new RiskReading(next, m, alerts); + } + + /// No new entries: the 24-hour block after a day's loss, or the switch tripped by the fall from the high. + public static bool EntriesBlocked(RiskMonitorState state, DateTimeOffset now) + { + ArgumentNullException.ThrowIfNull(state); + return state.Tripped || state.DailyBlockUntil > now; + } + + ///+ /// The multiplier on purchases: halved for seven days after a week's loss, halved while the fall from the high is + /// beyond its first threshold, both together a quarter. Never above one (SPEC 9.1 point 5). + /// + public static decimal Multiplier(RiskMonitorState state, RiskMeasures m, DateTimeOffset now, RiskLimits limits) + { + ArgumentNullException.ThrowIfNull(state); + ArgumentNullException.ThrowIfNull(m); + ArgumentNullException.ThrowIfNull(limits); + var multiplier = 1m; + if (state.WeeklyHalvingUntil > now) + { + multiplier *= 0.5m; + } + + if (m.Drawdown <= -limits.DrawdownHalf) + { + multiplier *= 0.5m; + } + + return multiplier; + } + + ///+ /// The user's confirmed restart after a trip (SPEC 9.3): the switch is reset and, when the trip came from the fall + /// from the high, the high starts again from now, or the switch would trip again at once. + /// + public static RiskMonitorState Restart(RiskMonitorState state, DateTimeOffset now) + { + ArgumentNullException.ThrowIfNull(state); + return state with + { + Tripped = false, + TrippedAt = null, + PeakFrom = state.Tripped ? now : state.PeakFrom, + Peak = state.Tripped ? null : state.Peak, + Warned = [.. state.Warned.Where(w => !w.StartsWith("drawdown", StringComparison.Ordinal))], + }; + } + + public static string Percent(decimal change) => (change * 100m).ToString("0.0", Italian) + "%"; +} diff --git a/src/Anubis/Risk/RiskRules.cs b/src/Anubis/Risk/RiskRules.cs new file mode 100644 index 0000000..b722a09 --- /dev/null +++ b/src/Anubis/Risk/RiskRules.cs @@ -0,0 +1,155 @@ +namespace Anubis.Risk; + +///Reason codes of the risk engine: every reduction and every refusal leaves one (SPEC 5.2). +public static class RiskReasons +{ + public const string Reduction = "risk_reduction"; + public const string DailyLossBlock = "daily_loss_block"; + public const string SwitchTripped = "switch_tripped"; + public const string BotPaused = "bot_paused"; + public const string BotStopped = "bot_stopped"; + public const string InvestedLimit = "invested_limit"; + public const string PositionLimit = "position_limit"; + public const string CryptoLimit = "crypto_limit"; + public const string TradeRiskLimit = "trade_risk_limit"; + public const string StopAbovePrice = "stop_above_price"; + public const string StalePrice = "stale_price"; + public const string PriceGap = "price_gap"; + public const string ClockSkew = "clock_skew"; + public const string OwnedByOther = "owned_by_other_strategy"; + public const string NoShortSelling = "no_short_selling"; + public const string NoLeverage = "no_leverage"; + public const string NotOwned = "not_owned_by_bot"; + public const string LiveNotConfirmed = "live_not_confirmed"; + public const string ExitOnly = "exit_only"; + public const string NoConsent = "live_not_allowed"; + public const string Observation = "observation"; + public const string OrdersPerMinute = "orders_per_minute"; +} + +///+/// A purchase as the risk engine sees it, every amount in one currency. +public sealed record PurchaseRequest +{ + public required decimal Price { get; init; } + + public required decimal Held { get; init; } + + public required decimal Wanted { get; init; } + + ///is the reference +/// equity of SPEC 9.2 (a quarter of it for a strategy in reduced real); and +/// are those of the world the order belongs to. +/// The stop of the whole position after the purchase; null means none, and the risk is the whole position. + public decimal? Stop { get; init; } + + ///Product of the reductions in force (correctives and loss limits): one or less. + public decimal Multiplier { get; init; } = 1m; + + public required decimal WorldEquity { get; init; } + + public required decimal WorldInvested { get; init; } + + public required decimal Reference { get; init; } + + public bool IsCrypto { get; init; } + + ///Crypto already held by the bot, on every account of the world. + public decimal CryptoValue { get; init; } +} + +public sealed record PurchaseSize(decimal Quantity, IReadOnlyListReasons) +{ + public bool Reduced => Reasons.Count > 0; +} + +/// +/// The size rules of SPEC 9.2 on one purchase, in a fixed order. Each can only make the purchase smaller: none of +/// them, nor all together, can make it larger than what the strategy asked (SPEC 9.1 point 6). +/// +public static class RiskRules +{ + public static PurchaseSize SizePurchase(PurchaseRequest r, RiskLimits limits) + { + ArgumentNullException.ThrowIfNull(r); + ArgumentNullException.ThrowIfNull(limits); + var reasons = new List(); + var q = Math.Max(0m, r.Wanted); + if (r.Price <= 0m || q == 0m) + { + return new PurchaseSize(0m, reasons); + } + + void Cap(decimal room, string reason) + { + var most = Math.Max(0m, room); + if (q > most) + { + q = most; + reasons.Add(reason); + } + } + + // A reduction multiplies the target, not what is already held: a halved purchase is not completed while the + // halving lasts, and nothing already held is sold for it (SPEC 8.5). + var multiplier = Math.Clamp(r.Multiplier, 0m, 1m); + if (multiplier < 1m) + { + Cap(Math.Max(r.Held, multiplier * (r.Held + r.Wanted)) - r.Held, RiskReasons.Reduction); + } + + Cap(((limits.MaxInvested * r.WorldEquity) - r.WorldInvested) / r.Price, RiskReasons.InvestedLimit); + Cap((limits.MaxPosition * r.Reference / r.Price) - r.Held, RiskReasons.PositionLimit); + if (r.IsCrypto) + { + Cap(((limits.MaxCrypto * r.Reference) - r.CryptoValue) / r.Price, RiskReasons.CryptoLimit); + } + + if (r.Stop is { } stop && stop >= r.Price) + { + Cap(0m, RiskReasons.StopAbovePrice); + } + else + { + // The loss if the stop of the whole position triggered; without a stop, the whole position. + var distance = r.Stop is > 0m and var s ? r.Price - s : r.Price; + Cap((limits.MaxTradeRisk * r.Reference / distance) - r.Held, RiskReasons.TradeRiskLimit); + } + + return new PurchaseSize(q, reasons); + } + + /// What to sell of a position heavier than the threshold, to bring it back to it; zero when it is within. + public static decimal Excess(decimal held, decimal price, decimal reference, RiskLimits limits) + { + ArgumentNullException.ThrowIfNull(limits); + if (held <= 0m || price <= 0m || reference <= 0m) + { + return 0m; + } + + return Math.Max(0m, held - (limits.MaxPosition * reference / price)); + } + + ///The technical checks of SPEC 9.2: they stop entries only, never stops and sales (trap 25). + public static string? TechnicalRefusal(DateTimeOffset now, DateTimeOffset? priceAt, decimal? lastPrice, decimal? limitPrice, TimeSpan? clockSkew, RiskLimits limits) + { + ArgumentNullException.ThrowIfNull(limits); + if (priceAt is not { } at || now - at > limits.MaxPriceAge || lastPrice is not > 0m) + { + return RiskReasons.StalePrice; + } + + if (clockSkew is { } skew && skew.Duration() > limits.MaxClockSkew) + { + return RiskReasons.ClockSkew; + } + + if (limitPrice is { } limit && Math.Abs((limit / lastPrice.Value) - 1m) > limits.MaxPriceGap) + { + return RiskReasons.PriceGap; + } + + return null; + } +} diff --git a/src/Anubis/Risk/Scenarios.cs b/src/Anubis/Risk/Scenarios.cs new file mode 100644 index 0000000..de8b712 --- /dev/null +++ b/src/Anubis/Risk/Scenarios.cs @@ -0,0 +1,111 @@ +using System.Globalization; +using Anubis.Core; + +namespace Anubis.Risk; + +///A "what if it happened tomorrow" of SPEC 9.5: price changes of crypto and US stocks, and of the dollar on the euro. +public sealed record Scenario(string Label, decimal Crypto, decimal Stocks, decimal Dollar); + +///A position of the bot valued in euro, with the value it would have at its stop. +public sealed record ScenarioPosition(bool IsCrypto, decimal ValueEur, decimal? ValueAtStopEur); + +public sealed record ScenarioResult(Scenario Scenario, decimal WithoutStops, decimal WithoutStopsShare, decimal? WithStops, bool SameWithStops); + +///+/// The scenarios of the Rischio screen (SPEC 9.5): a simple sum on the positions of the moment. "Without stops" +/// applies the change to the whole value of the positions involved; "with the stops" takes for each position the +/// smaller loss between the scenario and the distance from its stop, rounded to 5 € and shown as "about", because a +/// stop does not guarantee the price. The dollar scenario applies to the value of the dollar account, stops do not +/// reduce it. +/// +public static class Scenarios +{ + public static readonly IReadOnlyListDefault = + [ + new("Le crypto perdono il 20% in un giorno", -0.20m, 0m, 0m), + new("Le azioni USA perdono il 7%", 0m, -0.07m, 0m), + new("Le due cose insieme", -0.20m, -0.07m, 0m), + new("Il dollaro perde il 5% sull'euro", 0m, 0m, -0.05m), + ]; + + /// The scenarios as a setting, one per line: + public static readonly SettingDefinition Setting = new("risk.scenarios", "Scenari \"Se succedesse domani\"", Write(Default), Check: Check); + + public static IReadOnlyListlabel; crypto %; stocks %; dollar % .Compute(IReadOnlyList scenarios, IReadOnlyList positions, decimal dollarAccountEur, decimal equityEur) + { + ArgumentNullException.ThrowIfNull(scenarios); + ArgumentNullException.ThrowIfNull(positions); + var result = new List (); + foreach (var s in scenarios) + { + var without = 0m; + var with = 0m; + foreach (var p in positions) + { + var change = p.IsCrypto ? s.Crypto : s.Stocks; + if (change >= 0m) + { + continue; + } + + var loss = p.ValueEur * change; + without += loss; + var toStop = p.ValueAtStopEur is { } atStop ? Math.Min(0m, atStop - p.ValueEur) : loss; + with += Math.Max(loss, toStop); + } + + var dollar = dollarAccountEur * Math.Min(0m, s.Dollar); + without += dollar; + with += dollar; + var sameWithStops = s.Crypto >= 0m && s.Stocks >= 0m; + result.Add(new ScenarioResult(s, Math.Round(without, 2), equityEur > 0m ? without / equityEur : 0m, + sameWithStops ? null : Math.Round(with / 5m, MidpointRounding.AwayFromZero) * 5m, sameWithStops)); + } + + return result; + } + + public static IReadOnlyList Parse(string text) + { + ArgumentNullException.ThrowIfNull(text); + var list = new List (); + foreach (var line in text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + var parts = line.Split(';', StringSplitOptions.TrimEntries); + if (parts.Length != 4 || parts[0].Length == 0) + { + throw new FormatException("Ogni riga: descrizione; crypto %; azioni %; dollaro %."); + } + + list.Add(new Scenario(parts[0], Number(parts[1]) / 100m, Number(parts[2]) / 100m, Number(parts[3]) / 100m)); + } + + return list; + } + + public static string Write(IReadOnlyList scenarios) + { + ArgumentNullException.ThrowIfNull(scenarios); + return string.Join('\n', scenarios.Select(s => string.Join("; ", s.Label, Text(s.Crypto), Text(s.Stocks), Text(s.Dollar)))); + } + + private static string? Check(string text) + { + try + { + var list = Parse(text); + return list.Count is 0 or > 8 ? "Da uno a otto scenari." : list.Any(s => s.Crypto is < -1m or > 1m || s.Stocks is < -1m or > 1m || s.Dollar is < -1m or > 1m) + ? "Le variazioni vanno da −100 a +100." + : null; + } + catch (FormatException ex) + { + return ex.Message; + } + } + + private static decimal Number(string text) => + decimal.TryParse(text.Replace(',', '.').Replace('−', '-'), NumberStyles.Number, CultureInfo.InvariantCulture, out var v) ? v : throw new FormatException("Numero non valido: " + text); + + private static string Text(decimal fraction) => (fraction * 100m).ToString("0.##", CultureInfo.InvariantCulture); +} diff --git a/src/Anubis/Strategies/Correctives.cs b/src/Anubis/Strategies/Correctives.cs new file mode 100644 index 0000000..a40645b --- /dev/null +++ b/src/Anubis/Strategies/Correctives.cs @@ -0,0 +1,250 @@ +using Anubis.Data; + +namespace Anubis.Strategies; + +/// Reason codes of the correctives (SPEC 8.5): each intervention leaves its own. +public static class CorrectiveReasons +{ + public const string CryptoRegimeAverage = "crypto_regime_below_average"; + public const string CryptoRegimeVolatility = "crypto_regime_high_volatility"; + public const string CalendarEvent = "calendar_event"; +} + +///Weights of the strategy's book at the moment of the decision, as the correctives and the risk engine read them. +public static class BookWeights +{ + ///The last price of an instrument: today's close, or the average price when there are no bars. + public static decimal Price(StrategyContext context, string symbol) + { + ArgumentNullException.ThrowIfNull(context); + var bars = context.Bars(symbol); + return bars.Count > 0 ? (decimal)bars.Close(bars.Count - 1) : context.Portfolio.Of(symbol)?.AveragePrice ?? 0m; + } + + public static decimal Current(StrategyContext context, string symbol) + { + ArgumentNullException.ThrowIfNull(context); + var holding = context.Portfolio.Of(symbol); + var equity = context.Portfolio.Equity; + return holding is not { Quantity: > 0m } || equity <= 0m ? 0m : holding.Quantity * Price(context, symbol) / equity; + } + + ///+ /// A reduction of SPEC 8.5 on one intent: the multiplier applies to the target, never to what is held, so a + /// halved purchase is not completed while the halving lasts and nothing is sold because of it. Exits, decreases + /// and stop updates pass unchanged. + /// + public static Intent Reduce(StrategyContext context, Intent intent, decimal multiplier, string code) + { + ArgumentNullException.ThrowIfNull(intent); + if (intent.TargetWeight is not { } target || multiplier >= 1m) + { + return intent; + } + + var current = Current(context, intent.Symbol); + if (target <= current) + { + return intent; + } + + var reduced = Math.Max(current, Math.Round(Math.Max(0m, multiplier) * target, 6, MidpointRounding.ToZero)); + if (reduced <= current) + { + // Nothing more to buy: a position stays as it is, its stop still following the strategy; a new entry + // stays in the record with its reason code and does nothing. + return current > 0m + ? (intent with { TargetWeight = null }).Adjusted(code) + : (intent with { TargetWeight = null, Stop = null, StopOffset = null }).Adjusted(code); + } + + return (intent with { TargetWeight = reduced }).Adjusted(code); + } +} + +public sealed record CryptoRegimeSettings +{ + public int AverageDays { get; init; } = 200; + + ///Volatility measured on 30 daily returns, compared with its own values of the last two years. + public int VolatilityDays { get; init; } = 30; + + public int PercentileDays { get; init; } = 730; + + public double Percentile { get; init; } = 0.9; + + ///Fewer values than this and the percentile is not used: a year is the least to call something high. + public int MinPercentileDays { get; init; } = 365; + + public decimal Multiplier { get; init; } = 0.5m; +} + +///+/// The crypto regime of SPEC 8.5: when Bitcoin closes below its 200-day average, or its volatility is above the 90th +/// percentile of the last two years, new entries of +public static class CryptoRegime +{ + ///crypto_trend are halved. +///Null when the regime is calm, otherwise the reason code. + public static string? Risky(BarSeries btc, CryptoRegimeSettings settings) + { + ArgumentNullException.ThrowIfNull(btc); + ArgumentNullException.ThrowIfNull(settings); + if (btc.Count == 0) + { + return null; + } + + if (Indicators.Sma(btc, settings.AverageDays) is { } average && btc.Close(btc.Count - 1) < average) + { + return CorrectiveReasons.CryptoRegimeAverage; + } + + var vols = RollingVolatility(btc, settings.VolatilityDays, settings.PercentileDays); + if (vols.Length < settings.MinPercentileDays) + { + return null; + } + + var today = vols[^1]; + var sorted = vols.Order().ToArray(); + var threshold = sorted[(int)Math.Min(sorted.Length - 1, Math.Floor(settings.Percentile * (sorted.Length - 1)))]; + return today > threshold ? CorrectiveReasons.CryptoRegimeVolatility : null; + } + + ///Standard deviation of the last + public static double[] RollingVolatility(BarSeries bars, int window, int days) + { + ArgumentNullException.ThrowIfNull(bars); + var n = bars.Count; + var available = n - window; + if (available <= 0) + { + return []; + } + + var count = Math.Min(days, available); + var first = n - count - window; + var returns = new double[count + window - 1]; + for (var i = 0; i < returns.Length; i++) + { + returns[i] = Math.Log(bars.Close(first + i + 1) / bars.Close(first + i)); + } + + var result = new double[count]; + double sum = 0, squares = 0; + for (var i = 0; i < returns.Length; i++) + { + sum += returns[i]; + squares += returns[i] * returns[i]; + if (i >= window) + { + sum -= returns[i - window]; + squares -= returns[i - window] * returns[i - window]; + } + + if (i >= window - 1 && i - (window - 1) < count) + { + var mean = sum / window; + result[i - (window - 1)] = Math.Sqrt(Math.Max(0, (squares - (window * mean * mean)) / (window - 1))); + } + } + + return result; + } +} + +///daily log returns, for each of the last days. The crypto regime as a step of the decision: it reduces the entries of the strategy it is given to. +public sealed class CryptoRegimeStage(string bitcoin, CryptoRegimeSettings? settings = null) : IIntentStage +{ + private readonly CryptoRegimeSettings _settings = settings ?? new CryptoRegimeSettings(); + + public string Name => "crypto_regime"; + + public IReadOnlyListApply(StrategyContext context, IReadOnlyList intents) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(intents); + if (!intents.Any(i => i.TargetWeight > 0m) || CryptoRegime.Risky(context.Bars(bitcoin), _settings) is not { } code) + { + return intents; + } + + return [.. intents.Select(i => BookWeights.Reduce(context, i, _settings.Multiplier, code))]; + } +} + +/// +/// The calendar of SPEC 8.5: no new entries from 30 minutes before to 30 minutes after a high-impact US figure, and +/// to 60 minutes after a Fed or ECB decision. A blocked entry is tried again at the end of the window in the same +/// session; when the session ends first it is dropped. Crypto has no sessions: the deadline is 12:00 UTC of the day. +/// +public static class CalendarBlocks +{ + public static TimeSpan Before { get; } = TimeSpan.FromMinutes(30); + + public static TimeSpan After { get; } = TimeSpan.FromMinutes(30); + + public static TimeSpan AfterCentralBank { get; } = TimeSpan.FromMinutes(60); + + ///The window of an event that blocks entries, or null for one that does not (low impact, another currency, no time). + public static (DateTimeOffset From, DateTimeOffset To)? Window(CalendarEvent e) + { + ArgumentNullException.ThrowIfNull(e); + if (!e.TimeKnown) + { + return null; + } + + return e.Kind switch + { + CalendarEventKinds.CentralBank => (e.OccursAt - Before, e.OccursAt + AfterCentralBank), + CalendarEventKinds.Economic when e.Currency == "USD" && string.Equals(e.Impact, "High", StringComparison.OrdinalIgnoreCase) => (e.OccursAt - Before, e.OccursAt + After), + _ => null, + }; + } + + ///The end of the block + public static DateTimeOffset? BlockedUntil(DateTimeOffset at, IEnumerablefalls in, following windows that overlap; null when there is none. events) + { + ArgumentNullException.ThrowIfNull(events); + var windows = events.Select(Window).OfType<(DateTimeOffset From, DateTimeOffset To)>().OrderBy(w => w.From).ToList(); + DateTimeOffset? until = null; + var moment = at; + foreach (var (from, to) in windows) + { + if (from <= moment && to > moment) + { + until = to; + moment = to; + } + } + + return until; + } + + /// When a blocked entry is tried again; null means it is dropped, with its reason code. + public static DateTimeOffset? RetryAt(DateTimeOffset at, IEnumerableevents, DateTimeOffset deadline) => + BlockedUntil(at, events) is { } end ? end <= deadline ? end : null : at; + + /// The deadline of a crypto entry (SPEC 5.6): 12:00 UTC of the same day. + public static DateTimeOffset CryptoDeadline(DateTimeOffset at) => new(at.UtcDateTime.Date.AddHours(12), TimeSpan.Zero); +} + +///The calendar block as a step of the decision: during a window no intent may increase a position. +public sealed class CalendarStage(Func> events) : IIntentStage +{ + public string Name => "calendar"; + + public IReadOnlyList Apply(StrategyContext context, IReadOnlyList intents) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(intents); + if (!intents.Any(i => i.TargetWeight > 0m) || CalendarBlocks.BlockedUntil(context.Now, events(context.Now)) is null) + { + return intents; + } + + return [.. intents.Select(i => BookWeights.Reduce(context, i, 0m, CorrectiveReasons.CalendarEvent))]; + } +} diff --git a/src/Anubis/Strategies/CryptoTrend.cs b/src/Anubis/Strategies/CryptoTrend.cs new file mode 100644 index 0000000..c1b459a --- /dev/null +++ b/src/Anubis/Strategies/CryptoTrend.cs @@ -0,0 +1,478 @@ +using System.Globalization; +using Anubis.Data; + +namespace Anubis.Strategies; + +/// The fixed rules of +public sealed record CryptoTrendSettings +{ + public IReadOnlyListcrypto_trend (SPEC 8.1). Only the two family parameters move in a test.Periods { get; init; } = [5, 10, 20, 30, 60, 90, 150, 250, 360]; + + /// Volatility each coin is sized to: raw weight = e × this / its volatility. + public double CoinVolatility { get; init; } = 0.15; + + ///Above this estimated volatility of the whole strategy, every weight shrinks by one factor. + public double StrategyVolatility { get; init; } = 0.20; + + ///The server stop is never further than this below the last close. + public double MaxStop { get; init; } = 0.15; + + public decimal MajorCap { get; init; } = 0.35m; + + public decimal OtherCap { get; init; } = 0.20m; + + public IReadOnlySetMajors { get; init; } = new HashSet (StringComparer.OrdinalIgnoreCase) { "BTC", "ETH" }; + + public int VolatilityWindow { get; init; } = 90; + + /// A position is resized only when it is this far from its target, relative to the target… + public decimal RebalanceRelative { get; init; } = 0.20m; + + ///…and this far in share of the strategy's capital. + public decimal RebalanceMinimum { get; init; } = 0.005m; + + public int UniverseSize { get; init; } = CryptoUniverse.Size; + + public int MinAgeDays { get; init; } = CryptoUniverse.MinAgeDays; + + public double MinValue { get; init; } = CryptoUniverse.MinValueEur; + + public double MaxSpreadBp { get; init; } = CryptoUniverse.MaxSpreadBp; + + public int ValueWindow { get; init; } = CryptoUniverse.Window; +} + +///+/// +public sealed class CryptoTrend(CryptoTrendSettings? settings = null) : IStrategy +{ + private readonly CryptoTrendSettings _settings = settings ?? new CryptoTrendSettings(); + private readonly Dictionarycrypto_trend (SPEC 8.1): Donchian channels on nine periods. A period turns on when a close beats the highest +/// of its previous N closes, with a trailing stop at the middle of the last N closes that can only rise, and turns off +/// when a close ends below yesterday's stop. The average of the nine states,e , sizes each coin against its +/// volatility. The state depends on the whole history: it is rebuilt by walking the daily bars with the backtest's +/// rules, and kept between decisions so each bar is walked once. +///_trackers = new(StringComparer.Ordinal); + private (string Key, IReadOnlyList Members)? _universe; + + public string Id => CryptoTrendFamily.FamilyId; + + public string Version => CryptoTrendFamily.FamilyVersion; + + public CryptoTrendSettings Settings => _settings; + + /// Once a day on the 00:00 UTC close (SPEC 8.1); orders go right after. + public IReadOnlyListSchedule() => [DecisionTime.AfterClose]; + + /// + /// The 10 coins with the highest median traded value over 30 days on the first day of the month, among those + /// listed for 400 days, above the minimum value and, live, below the maximum spread; no stablecoins, wrapped or + /// leveraged tokens. The same for the whole month. + /// + public IReadOnlyListUniverse(UniverseContext context) + { + ArgumentNullException.ThrowIfNull(context); + var month = new DateOnly(context.Day.Year, context.Day.Month, 1); + if (context.Members?.Invoke(Id, month) is { } saved) + { + return saved; + } + + var key = month.ToString("yyyy-MM", CultureInfo.InvariantCulture) + "|" + string.Join(',', context.Available); + if (_universe is { } cached && cached.Key == key) + { + return cached.Members; + } + + var ranked = new List<(string Symbol, double Value)>(); + foreach (var symbol in context.Available) + { + if (context.Spec(symbol) is not { } spec || spec.AssetClass != AssetClasses.Crypto || CryptoUniverse.Excluded(Symbols.BaseOf(spec))) + { + continue; + } + + var bars = context.Bars(symbol); + var index = bars.IndexThrough(month); + if (index < _settings.ValueWindow - 1 || bars.Day(index) < month.AddDays(-3)) + { + continue; // Too little history, or not trading any more on that day. + } + + var listed = spec.ListedAt is { } at ? DateOnly.FromDateTime(at.UtcDateTime) : bars.FirstDay!.Value; + if (listed > month.AddDays(-_settings.MinAgeDays)) + { + continue; + } + + var value = Indicators.MedianValue(bars, _settings.ValueWindow, index) ?? 0; + if (value <= _settings.MinValue) + { + continue; + } + + if (context.SpreadBp is { } spread && (spread(symbol) is not { } bp || bp >= _settings.MaxSpreadBp)) + { + continue; // Live only: an unknown spread counts as too wide. + } + + ranked.Add((symbol, value)); + } + + var members = ranked.OrderByDescending(r => r.Value).ThenBy(r => r.Symbol, StringComparer.Ordinal) + .Take(_settings.UniverseSize).Select(r => r.Symbol).ToList(); + _universe = (key, members); + return members; + } + + public IReadOnlyList Decide(StrategyContext context) + { + ArgumentNullException.ThrowIfNull(context); + var equity = context.Portfolio.Equity; + if (equity <= 0m) + { + return []; + } + + // Coins of the universe, and coins held that left it: those stay managed until their signal exits. + var inUniverse = new HashSet (context.Universe, StringComparer.Ordinal); + var symbols = context.Universe.Concat(context.Portfolio.Holdings.Where(h => h.Value.Quantity > 0m).Select(h => h.Key)) + .Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToList(); + + var rows = new List (); + foreach (var symbol in symbols) + { + var bars = context.Bars(symbol); + if (bars.Count == 0) + { + continue; + } + + var tracker = Tracker(symbol).Advance(bars, _settings); + var close = bars.Close(bars.Count - 1); + var holding = context.Portfolio.Of(symbol); + var current = holding is { Quantity: > 0m } h && close > 0 ? h.Quantity * (decimal)close / equity : 0m; + var weight = 0d; + var volatility = Indicators.Volatility(bars, _settings.VolatilityWindow, 365); + if (tracker.Ensemble > 0 && volatility is > 0) + { + var cap = _settings.Majors.Contains(Symbols.BaseOf(context.Spec(symbol), symbol)) ? _settings.MajorCap : _settings.OtherCap; + weight = Math.Min(tracker.Ensemble * _settings.CoinVolatility / volatility.Value, (double)cap); + } + + rows.Add(new Row(symbol, bars, tracker, holding, current, weight, inUniverse.Contains(symbol))); + } + + // Caps first; then, if the weights add up to more than everything, all shrink in proportion; then one factor + // for the volatility of the whole strategy. What is cut stays cash. + var total = rows.Sum(r => r.Weight); + if (total > 1) + { + foreach (var r in rows) + { + r.Weight /= total; + } + } + + var portfolio = Indicators.PortfolioVolatility([.. rows.Where(r => r.Weight > 0).Select(r => (r.Bars, r.Weight))], _settings.VolatilityWindow, 365); + if (portfolio is > 0 && portfolio.Value > _settings.StrategyVolatility) + { + var factor = _settings.StrategyVolatility / portfolio.Value; + foreach (var r in rows) + { + r.Weight *= factor; + } + } + + var intents = new List
(); + foreach (var r in rows) + { + var target = Math.Round((decimal)r.Weight, 6, MidpointRounding.ToZero); + if (!r.InUniverse) + { + target = Math.Min(target, r.Current); // Out of the universe: managed, never bought. + } + + var stop = r.Tracker.ServerStop is { } s ? (decimal?)Math.Round((decimal)s, 8) : null; + var held = r.Holding is { Quantity: > 0m }; + if (held && target <= 0m) + { + intents.Add(new Intent(r.Symbol, 0m, Reasons.Exit)); + } + else if (!held && target > 0m) + { + if (target > _settings.RebalanceMinimum) + { + intents.Add(new Intent(r.Symbol, target, Reasons.Entry) { Stop = stop }); + } + } + else if (held) + { + var gap = Math.Abs(target - r.Current); + if (gap > _settings.RebalanceRelative * target && gap > _settings.RebalanceMinimum) + { + intents.Add(new Intent(r.Symbol, target, target > r.Current ? Reasons.Increase : Reasons.Reduce) { Stop = stop }); + } + else if (stop is not null && stop != r.Holding!.Stop) + { + intents.Add(new Intent(r.Symbol, null, Reasons.StopMoved) { Stop = stop }); + } + } + } + + return intents; + } + + /// The state of a coin as of its last bar walked: the nine periods, + public TrendTracker Tracker(string symbol) + { + if (!_trackers.TryGetValue(symbol, out var tracker)) + { + tracker = new TrendTracker(); + _trackers[symbol] = tracker; + } + + return tracker; + } + + public static class Reasons + { + public const string Entry = "trend_entry"; + public const string Increase = "trend_increase"; + public const string Reduce = "trend_reduce"; + public const string Exit = "trend_exit"; + public const string StopMoved = "trend_stop"; + } + + private sealed class Row(string symbol, BarSeries bars, TrendTracker tracker, Holding? holding, decimal current, double weight, bool inUniverse) + { + public string Symbol { get; } = symbol; + + public BarSeries Bars { get; } = bars; + + public TrendTracker Tracker { get; } = tracker; + + public Holding? Holding { get; } = holding; + + public decimal Current { get; } = current; + + public double Weight { get; set; } = weight; + + public bool InUniverse { get; } = inUniverse; + } +} + +///e , the server stop.+/// The Donchian states of one coin (SPEC 8.1), walked one daily bar at a time. Walking the same bars always gives the +/// same state: from scratch on the first start, or from the saved state and the bars missing since. +/// +public sealed class TrendTracker +{ + private bool[] _active = []; + private double[] _stops = []; + private int _walked; + private DateOnly? _first; + private DateOnly? _last; + + ///The average of the period states, between 0 and 1. + public double Ensemble { get; private set; } + + ///The level of the stop on the broker; null when no period is on. + public double? ServerStop { get; private set; } + + ///The day of the last bar walked. + public DateOnly? LastDay => _last; + + public IReadOnlyListActive => _active; + + /// Walks the bars not walked yet. A history that does not continue the one walked starts again. + public TrendTracker Advance(BarSeries bars, CryptoTrendSettings settings) + { + ArgumentNullException.ThrowIfNull(bars); + ArgumentNullException.ThrowIfNull(settings); + if (_active.Length != settings.Periods.Count || bars.Count < _walked || (_walked > 0 && (bars.FirstDay != _first || bars.Day(_walked - 1) != _last))) + { + Reset(settings); + } + + for (var i = _walked; i < bars.Count; i++) + { + Step(bars, i, settings); + } + + _walked = bars.Count; + _first = bars.FirstDay; + _last = bars.LastDay; + return this; + } + + private void Reset(CryptoTrendSettings settings) + { + _active = new bool[settings.Periods.Count]; + _stops = new double[settings.Periods.Count]; + _walked = 0; + _first = null; + _last = null; + Ensemble = 0; + ServerStop = null; + } + + private void Step(BarSeries bars, int i, CryptoTrendSettings settings) + { + var close = bars.Close(i); + // The stop on the broker, touched by the low of the day: every period of the coin goes back to 0 and a new + // high is needed to come back. The backtest applies the same rule (SPEC 8.1). + if (Ensemble > 0 && ServerStop is { } server && bars.Low(i) <= server) + { + Array.Clear(_active); + Ensemble = 0; + ServerStop = null; + } + + var activated = false; + for (var k = 0; k < settings.Periods.Count; k++) + { + var n = settings.Periods[k]; + if (i < n) + { + continue; // Not N previous closes yet. + } + + if (_active[k]) + { + if (close < _stops[k]) + { + _active[k] = false; // A close below yesterday's stop. + continue; + } + + _stops[k] = Math.Max(_stops[k], Middle(bars, i, n)); + } + else if (close > HighestBefore(bars, i, n)) + { + _active[k] = true; + _stops[k] = Middle(bars, i, n); + activated = true; + } + } + + var on = 0; + var lowest = double.MaxValue; + for (var k = 0; k < _active.Length; k++) + { + if (_active[k]) + { + on++; + lowest = Math.Min(lowest, _stops[k]); + } + } + + Ensemble = (double)on / _active.Length; + if (on == 0) + { + ServerStop = null; + return; + } + + // Where every active period would have left, but never more than the maximum below the close. It can only rise, + // except when a period turns on and brings a lower stop with it. + var candidate = Math.Max(lowest, close * (1 - settings.MaxStop)); + ServerStop = ServerStop is { } previous && !activated ? Math.Max(previous, candidate) : candidate; + } + + ///The highest of the N closes before bar i. + private static double HighestBefore(BarSeries bars, int i, int n) + { + var high = double.MinValue; + for (var j = i - n; j < i; j++) + { + high = Math.Max(high, bars.Close(j)); + } + + return high; + } + + ///The middle between the highest and the lowest of the last N closes, bar i included. + private static double Middle(BarSeries bars, int i, int n) + { + double high = double.MinValue, low = double.MaxValue; + for (var j = i - n + 1; j <= i; j++) + { + var c = bars.Close(j); + high = Math.Max(high, c); + low = Math.Min(low, c); + } + + return (high + low) / 2; + } +} + +public sealed class CryptoTrendFamily : IStrategyFamily +{ + public const string FamilyId = "crypto_trend"; + + public const string FamilyVersion = "1"; + + public static CryptoTrendFamily Instance { get; } = new(); + + public string Id => FamilyId; + + public string Version => FamilyVersion; + + public string Name => "Trend crypto"; + + public string Description => + "Segue la tendenza delle 10 crypto più scambiate in euro. Compra quando il prezzo supera i massimi recenti su nove orizzonti, da 5 a 360 giorni, " + + "e più orizzonti sono d'accordo più compra; pesa meno le monete più agitate. Esce quando il prezzo scende sotto lo stop, che sale con il prezzo."; + + public IReadOnlyListParameters => + [ + new("coin_vol", "Volatilità obiettivo per moneta (%)", 15m, [10m, 15m, 20m], 1m, 100m, Whole: true), + new("max_stop", "Stop al massimo sotto la chiusura (%)", 15m, [10m, 15m, 20m], 2m, 50m, Whole: true), + ]; + + public IStrategy Create(StrategyParameters parameters) + { + ArgumentNullException.ThrowIfNull(parameters); + return new CryptoTrend(new CryptoTrendSettings + { + CoinVolatility = (double)parameters["coin_vol"] / 100, + MaxStop = (double)parameters["max_stop"] / 100, + }); + } +} + +/// Reading the coin or company behind a symbol. +public static class Symbols +{ + private static readonly string[] Quotes = ["USDT", "USDC", "EUR", "USD", "BTC"]; + + ///The base currency of a pair: + public static string BaseOf(InstrumentSpec spec) + { + ArgumentNullException.ThrowIfNull(spec); + return spec.BaseCurrency ?? BaseOf(spec.Symbol); + } + + public static string BaseOf(InstrumentSpec? spec, string symbol) => spec is null ? BaseOf(symbol) : BaseOf(spec); + + public static string BaseOf(string symbol) + { + ArgumentNullException.ThrowIfNull(symbol); + var dash = symbol.IndexOf('-', StringComparison.Ordinal); + if (dash > 0) + { + return symbol[..dash]; + } + + foreach (var quote in Quotes) + { + if (symbol.Length > quote.Length && symbol.EndsWith(quote, StringComparison.OrdinalIgnoreCase)) + { + return symbol[..^quote.Length]; + } + } + + return symbol; + } +} diff --git a/src/Anubis/Strategies/EquityStrategies.cs b/src/Anubis/Strategies/EquityStrategies.cs new file mode 100644 index 0000000..9092f0b --- /dev/null +++ b/src/Anubis/Strategies/EquityStrategies.cs @@ -0,0 +1,546 @@ +using Anubis.Data; + +namespace Anubis.Strategies; + +///BTC forBTC-EUR and forBTCUSDT .+/// The stock universe of SPEC 8.2 computed from the bars known on the day: common shares on NYSE and Nasdaq, +/// fractionable, no funds, real close above 10 $, at least 300 sessions, ranked by the median traded value of the last +/// 60 sessions. Live, the universe saved "as of the date" is used instead (SPEC 6.7). +/// +public static class EquityUniverseRanking +{ + public static IReadOnlyListRank(UniverseContext context, int size) + { + ArgumentNullException.ThrowIfNull(context); + var ranked = new List<(string Symbol, double Value)>(); + foreach (var symbol in context.Available) + { + if (context.Spec(symbol) is not { } spec || !EquityUniverse.Eligible(spec)) + { + continue; + } + + var bars = context.Bars(symbol); + var last = bars.Count - 1; + if (bars.Count < EquityUniverse.MinSessions || bars.Day(last) < context.Day.AddDays(-7) || bars.RealClose(last) <= EquityUniverse.MinPrice) + { + continue; + } + + ranked.Add((symbol, Indicators.MedianValue(bars, EquityUniverse.Window, last) ?? 0)); + } + + return [.. ranked.OrderByDescending(r => r.Value).ThenBy(r => r.Symbol, StringComparer.Ordinal).Take(size).Select(r => r.Symbol)]; + } + + /// Monday of the week of a day: two days are in the same week when their Mondays match. + public static DateOnly WeekOf(DateOnly day) => day.AddDays(-(((int)day.DayOfWeek + 6) % 7)); +} + +///The fixed rules of +public sealed record EquityMomentumSettings +{ + public int UniverseSize { get; init; } = EquityUniverse.Size; + + public IReadOnlyListequity_momentum (SPEC 8.2).Lookbacks { get; init; } = [63, 126, 252]; + + /// The returns skip the last sessions (short-term reversal). + public int Skip { get; init; } = 5; + + ///New entries among the first of the ranking… + public int Top { get; init; } = 12; + + ///…and a stock held leaves when it falls out of these. + public int Keep { get; init; } = 30; + + public int MaxPositions { get; init; } = 12; + + ///Each stock must close above its own average of these sessions. + public int Trend { get; init; } = 100; + + ///The market filter: SPY above its average of these sessions. + public int MarketTrend { get; init; } = 200; + + public string MarketSymbol { get; init; } = "SPY"; + + public int AtrLength { get; init; } = 20; + + public double AtrMultiple { get; init; } = 3; + + public int VolatilityWindow { get; init; } = 60; + + public double StrategyVolatility { get; init; } = 0.20; + + public decimal Cap { get; init; } = 0.15m; + + ///A position already open is resized only when this far from its target, relative to the target. + public decimal Rebalance { get; init; } = 0.25m; +} + +///+/// +public sealed class EquityMomentum(EquityMomentumSettings? settings = null) : IStrategy +{ + private readonly EquityMomentumSettings _settings = settings ?? new EquityMomentumSettings(); + + public string Id => EquityMomentumFamily.FamilyId; + + public string Version => EquityMomentumFamily.FamilyVersion; + + public EquityMomentumSettings Settings => _settings; + + public IReadOnlyListequity_momentum (SPEC 8.2): the strongest US stocks, only while the market rises. The weekly review runs on +/// the close of the last session before a new week, so its orders go at the open of the first session of the week +/// (live: 09:35 of that session, on the same data). Every close moves the trailing stops. +///Schedule() => [DecisionTime.AfterClose]; + + public IReadOnlyList Universe(UniverseContext context) + { + ArgumentNullException.ThrowIfNull(context); + return context.Members?.Invoke(Id, context.Day) ?? EquityUniverseRanking.Rank(context, _settings.UniverseSize); + } + + /// True when the next session opens a new week: the close of today is the time of the weekly review. + public static bool IsReview(StrategyContext context) + { + ArgumentNullException.ThrowIfNull(context); + return context.NextSession is { } next && EquityUniverseRanking.WeekOf(next) != EquityUniverseRanking.WeekOf(context.Day); + } + + public IReadOnlyListDecide(StrategyContext context) + { + ArgumentNullException.ThrowIfNull(context); + var equity = context.Portfolio.Equity; + var held = context.Portfolio.Holdings.Where(h => h.Value.Quantity > 0m).Select(h => h.Key).Order(StringComparer.Ordinal).ToList(); + var stops = new Dictionary (StringComparer.Ordinal); + foreach (var symbol in held) + { + if (TrailingStop(context, symbol) is { } stop) + { + stops[symbol] = stop; + } + } + + var intents = new SortedDictionary (StringComparer.Ordinal); + foreach (var (symbol, stop) in stops) + { + intents[symbol] = new Intent(symbol, null, Reasons.StopMoved) { Stop = stop }; + } + + if (!IsReview(context) || equity <= 0m) + { + return [.. intents.Values]; + } + + // The ranking: average of the 63, 126 and 252 session returns, each skipping the last 5 sessions. + var scores = new List<(string Symbol, double Score)>(); + foreach (var symbol in context.Universe) + { + var bars = context.Bars(symbol); + var parts = _settings.Lookbacks.Select(n => Indicators.Momentum(bars, n, _settings.Skip)).ToList(); + if (parts.All(p => p is not null)) + { + scores.Add((symbol, parts.Average(p => p!.Value))); + } + } + + var ranking = scores.OrderByDescending(s => s.Score).ThenBy(s => s.Symbol, StringComparer.Ordinal).Select(s => s.Symbol).ToList(); + var rank = ranking.Select((s, i) => (s, i)).ToDictionary(x => x.s, x => x.i, StringComparer.Ordinal); + bool AboveTrend(string symbol) + { + var bars = context.Bars(symbol); + return Indicators.Sma(bars, _settings.Trend) is { } average && bars.Count > 0 && bars.Close(bars.Count - 1) > average; + } + + var market = context.Bars(_settings.MarketSymbol); + var marketUp = Indicators.Sma(market, _settings.MarketTrend) is { } spyAverage && market.Close(market.Count - 1) > spyAverage; + + var keep = new List (); + foreach (var symbol in held) + { + if (!rank.TryGetValue(symbol, out var r) || r >= _settings.Keep) + { + intents[symbol] = new Intent(symbol, 0m, Reasons.ExitRank); + } + else if (!AboveTrend(symbol)) + { + intents[symbol] = new Intent(symbol, 0m, Reasons.ExitTrend); + } + else + { + keep.Add(symbol); + } + } + + // New entries only while SPY is above its average, and only among the first 12. + var entries = new List (); + if (marketUp) + { + foreach (var symbol in ranking.Take(_settings.Top)) + { + if (keep.Count + entries.Count >= _settings.MaxPositions) + { + break; + } + + if (!held.Contains(symbol) && AboveTrend(symbol)) + { + entries.Add(symbol); + } + } + } + + var weights = Weights(context, [.. keep, .. entries]); + foreach (var symbol in entries) + { + if (weights.GetValueOrDefault(symbol) is > 0m and var weight && Indicators.Atr(context.Bars(symbol), _settings.AtrLength) is { } atr) + { + intents[symbol] = new Intent(symbol, weight, Reasons.Entry) { StopOffset = Math.Round((decimal)(atr * _settings.AtrMultiple), 8) }; + } + } + + foreach (var symbol in keep) + { + var bars = context.Bars(symbol); + var holding = context.Portfolio.Of(symbol)!; + var current = holding.Quantity * (decimal)bars.Close(bars.Count - 1) / equity; + var target = weights.GetValueOrDefault(symbol, current); + if (!marketUp) + { + target = Math.Min(target, current); // With SPY below its average the strategy can only sell. + } + + if (Math.Abs(target - current) > _settings.Rebalance * target) + { + intents[symbol] = new Intent(symbol, target, target > current ? Reasons.Increase : Reasons.Reduce) { Stop = stops.GetValueOrDefault(symbol, holding.Stop ?? 0m) is > 0m and var s ? s : null }; + } + } + + return [.. intents.Values]; + } + + /// + /// Weights in inverse proportion to the 60-session volatility, the 15% cap (what it cuts stays cash), then one + /// factor, never above 1, when the strategy's estimated volatility is above 20% a year. + /// + private DictionaryWeights(StrategyContext context, IReadOnlyList members) + { + var inverse = new Dictionary (StringComparer.Ordinal); + foreach (var symbol in members) + { + if (Indicators.Volatility(context.Bars(symbol), _settings.VolatilityWindow, 252) is > 0 and var vol) + { + inverse[symbol] = 1 / vol; + } + } + + var sum = inverse.Values.Sum(); + var raw = inverse.ToDictionary(p => p.Key, p => Math.Min(p.Value / sum, (double)_settings.Cap), StringComparer.Ordinal); + var portfolio = Indicators.PortfolioVolatility([.. raw.Select(p => (context.Bars(p.Key), p.Value))], _settings.VolatilityWindow, 252); + var factor = portfolio is > 0 && portfolio.Value > _settings.StrategyVolatility ? _settings.StrategyVolatility / portfolio.Value : 1; + return raw.ToDictionary(p => p.Key, p => Math.Round((decimal)(p.Value * factor), 6, MidpointRounding.ToZero), StringComparer.Ordinal); + } + + /// 3 ATR(20) below the highest close since the entry; it can only rise. + private decimal? TrailingStop(StrategyContext context, string symbol) + { + var holding = context.Portfolio.Of(symbol)!; + var bars = context.Bars(symbol); + if (Indicators.Atr(bars, _settings.AtrLength) is not { } atr || Indicators.HighestCloseSince(bars, holding.EnteredOn) is not { } high) + { + return null; + } + + var candidate = Math.Round((decimal)(high - (_settings.AtrMultiple * atr)), 8); + if (candidate <= 0m || (holding.Stop is { } current && candidate <= current)) + { + return null; + } + + return candidate; + } + + public static class Reasons + { + public const string Entry = "momentum_entry"; + public const string Increase = "momentum_increase"; + public const string Reduce = "momentum_reduce"; + public const string ExitRank = "momentum_exit_rank"; + public const string ExitTrend = "momentum_exit_trend"; + public const string StopMoved = "momentum_stop"; + } +} + +public sealed class EquityMomentumFamily : IStrategyFamily +{ + public const string FamilyId = "equity_momentum"; + + public const string FamilyVersion = "1"; + + public static EquityMomentumFamily Instance { get; } = new(); + + public string Id => FamilyId; + + public string Version => FamilyVersion; + + public string Name => "Momentum azioni"; + + public string Description => + "Ogni settimana compra le azioni americane salite di più nell'ultimo anno, fino a 12, ma solo quando il mercato nel suo insieme sale. " + + "Vende quelle che perdono forza o scendono sotto la loro media; ognuna ha uno stop che sale con il prezzo."; + + public IReadOnlyListParameters => + [ + new("positions", "Numero massimo di titoli", 12m, [8m, 12m, 16m], 3m, 30m, Whole: true), + new("stop_atr", "Stop in ATR sotto il massimo", 3m, [2m, 3m, 4m], 1m, 10m, Whole: true), + ]; + + public IStrategy Create(StrategyParameters parameters) + { + ArgumentNullException.ThrowIfNull(parameters); + var positions = parameters.Whole("positions"); + return new EquityMomentum(new EquityMomentumSettings + { + Top = positions, + MaxPositions = positions, + AtrMultiple = (double)parameters["stop_atr"], + }); + } +} + +/// The fixed rules of +public sealed record EquityMeanrevSettings +{ + public int UniverseSize { get; init; } = 100; + + public int Trend { get; init; } = 200; + + public int RsiLength { get; init; } = 2; + + public double EntryRsi { get; init; } = 10; + + public double ExitRsi { get; init; } = 70; + + public int Fast { get; init; } = 5; + + public int MaxPositions { get; init; } = 3; + + ///equity_meanrev (SPEC 8.3).The entry session is the first: the time exit comes at the close of the fifth. + public int MaxSessions { get; init; } = 5; + + public int AtrLength { get; init; } = 14; + + public double AtrMultiple { get; init; } = 2.5; + + ///Risk of one operation, as a share of the reference equity of SPEC 9.2. + public decimal RiskPerTrade { get; init; } = 0.004m; + + public decimal Cap { get; init; } = 0.30m; + + ///The day-trade guard of SPEC 9.2, off by default: never exit on the entry day. + public bool PdtGuard { get; init; } + + ///Sessions after the entry in which an earnings report keeps the strategy out. + public int EarningsSessions { get; init; } = 3; +} + +///+/// +public sealed class EquityMeanrev(EquityMeanrevSettings? settings = null) : IStrategy +{ + private readonly EquityMeanrevSettings _settings = settings ?? new EquityMeanrevSettings(); + + public string Id => EquityMeanrevFamily.FamilyId; + + public string Version => EquityMeanrevFamily.FamilyVersion; + + public EquityMeanrevSettings Settings => _settings; + + public IReadOnlyListequity_meanrev (SPEC 8.3): buys the short dips of solid stocks. On the close, RSI(2) below 10 and the close +/// below its 5-session average; buys at the next open the lowest RSI, up to 3 positions. It exits at 15:55 (in the +/// backtest: the close) above the 5-session average, with RSI(2) above 70, before earnings, or at the fifth session. +///Schedule() => [DecisionTime.AfterClose]; + + /// The first 100 stocks of the universe of 8.2, in its order, that close above their 200-session average. + public IReadOnlyListUniverse(UniverseContext context) + { + ArgumentNullException.ThrowIfNull(context); + var ranked = context.Members?.Invoke(EquityMomentumFamily.FamilyId, context.Day) ?? EquityUniverseRanking.Rank(context, EquityUniverse.Size); + return [.. ranked.Where(s => + { + var bars = context.Bars(s); + return Indicators.Sma(bars, _settings.Trend) is { } average && bars.Close(bars.Count - 1) > average; + }).Take(_settings.UniverseSize)]; + } + + public IReadOnlyList Decide(StrategyContext context) + { + ArgumentNullException.ThrowIfNull(context); + var equity = context.Portfolio.Equity; + var intents = new List (); + var freeCash = context.Portfolio.Cash; + var open = 0; + foreach (var (symbol, holding) in context.Portfolio.Holdings.Where(h => h.Value.Quantity > 0m).OrderBy(h => h.Key, StringComparer.Ordinal)) + { + var bars = context.Bars(symbol); + if (bars.Count == 0) + { + open++; + continue; + } + + var close = bars.Close(bars.Count - 1); + var sessions = Indicators.SessionsSince(bars, holding.EnteredOn); + var reason = ExitReason(context, symbol, bars, close, sessions); + if (reason is not null && !(_settings.PdtGuard && sessions <= 1)) + { + intents.Add(new Intent(symbol, 0m, reason) { AtClose = true }); + freeCash += holding.Quantity * (decimal)close; // Sold at this close, before tomorrow's entries. + } + else + { + open++; + } + } + + var slots = _settings.MaxPositions - open; + if (slots <= 0 || equity <= 0m) + { + return intents; + } + + var candidates = new List<(string Symbol, double Rsi, double Close, double Atr)>(); + foreach (var symbol in context.Universe) + { + if (context.Portfolio.Holds(symbol) || context.Restricted?.Invoke(symbol) == true || EarningsAhead(context, symbol)) + { + continue; + } + + var bars = context.Bars(symbol); + if (Indicators.Rsi(bars, _settings.RsiLength) is not { } rsi || Indicators.Sma(bars, _settings.Fast) is not { } fast + || Indicators.Atr(bars, _settings.AtrLength) is not { } atr) + { + continue; + } + + var close = bars.Close(bars.Count - 1); + if (rsi < _settings.EntryRsi && close < fast) + { + candidates.Add((symbol, rsi, close, atr)); + } + } + + foreach (var c in candidates.OrderBy(c => c.Rsi).ThenBy(c => c.Symbol, StringComparer.Ordinal)) + { + if (slots == 0) + { + break; + } + + // Risk of 0.4% of the reference equity at the stop distance, capped at 30% of the strategy's capital. + var distance = Math.Round((decimal)(c.Atr * _settings.AtrMultiple), 8); + if (distance <= 0m) + { + continue; + } + + var value = _settings.RiskPerTrade * context.ReferenceEquity / distance * (decimal)c.Close; + value = Math.Min(value, _settings.Cap * equity); + if (value > freeCash) + { + continue; // Not enough free capital for this candidate: it is dropped. + } + + intents.Add(new Intent(c.Symbol, Math.Round(value / equity, 6, MidpointRounding.ToZero), Reasons.Entry) { StopOffset = distance }); + freeCash -= value; + slots--; + } + + return intents; + } + + private string? ExitReason(StrategyContext context, string symbol, BarSeries bars, double close, int sessions) + { + if (Indicators.Sma(bars, _settings.Fast) is { } fast && close > fast) + { + return Reasons.ExitAverage; + } + + if (Indicators.Rsi(bars, _settings.RsiLength) is > 0 and var rsi && rsi > _settings.ExitRsi) + { + return Reasons.ExitRsi; + } + + if (context.NextEarnings?.Invoke(symbol) is { } earnings && context.NextSession is { } next && earnings <= next) + { + return Reasons.ExitEarnings; // The report comes out by the close of the next session. + } + + return sessions >= _settings.MaxSessions ? Reasons.ExitTime : null; + } + + /// + /// Earnings in the entry session or the three after it, or out after today's close (live only: the backtest has no + /// earnings calendar, SPEC 8.3). + /// + private bool EarningsAhead(StrategyContext context, string symbol) + { + if (context.NextEarnings?.Invoke(symbol) is not { } earnings || context.NextSession is not { } entry) + { + return false; + } + + var last = entry; + for (var i = 0; i < _settings.EarningsSessions; i++) + { + last = last.AddDays(last.DayOfWeek == DayOfWeek.Friday ? 3 : 1); + } + + return earnings >= context.Day && earnings <= last; + } + + public static class Reasons + { + public const string Entry = "meanrev_entry"; + public const string ExitAverage = "meanrev_exit_average"; + public const string ExitRsi = "meanrev_exit_rsi"; + public const string ExitEarnings = "meanrev_exit_earnings"; + public const string ExitTime = "meanrev_exit_time"; + } +} + +public sealed class EquityMeanrevFamily : IStrategyFamily +{ + public const string FamilyId = "equity_meanrev"; + + public const string FamilyVersion = "1"; + + public static EquityMeanrevFamily Instance { get; } = new(); + + public string Id => FamilyId; + + public string Version => FamilyVersion; + + public string Name => "Mean reversion azioni"; + + public string Description => + "Compra le azioni solide, sopra la loro media di 200 giorni, dopo un calo di pochi giorni, e le rivende al primo rimbalzo o dopo cinque sedute. " + + "Al massimo 3 posizioni, ognuna con un rischio piccolo e uno stop fisso."; + + public IReadOnlyListParameters => + [ + new("entry_rsi", "RSI a 2 giorni per entrare (sotto)", 10m, [5m, 10m, 15m], 1m, 50m, Whole: true), + new("max_sessions", "Sedute al massimo in portafoglio", 5m, [3m, 5m, 7m], 1m, 20m, Whole: true), + ]; + + public IStrategy Create(StrategyParameters parameters) + { + ArgumentNullException.ThrowIfNull(parameters); + return new EquityMeanrev(new EquityMeanrevSettings + { + EntryRsi = (double)parameters["entry_rsi"], + MaxSessions = parameters.Whole("max_sessions"), + }); + } +} diff --git a/src/Anubis/Strategies/Indicators.cs b/src/Anubis/Strategies/Indicators.cs new file mode 100644 index 0000000..5a34ea1 --- /dev/null +++ b/src/Anubis/Strategies/Indicators.cs @@ -0,0 +1,264 @@ +namespace Anubis.Strategies; + +/// +/// The indicators of the strategies (SPEC 8), written in house (SPEC 2.7). Each reads a +public static class Indicators +{ + ///up to +/// its last bar, so it cannot look ahead. They return null when the history is too short: a strategy then does not +/// act on that instrument. +/// Simple average of the last + public static double? Sma(BarSeries bars, int length) => Sma(bars, length, bars?.Count - 1 ?? -1); + + ///closes. Simple average of the + public static double? Sma(BarSeries bars, int length, int end) + { + ArgumentNullException.ThrowIfNull(bars); + if (length <= 0 || end < length - 1 || end >= bars.Count) + { + return null; + } + + var sum = 0d; + for (var i = end - length + 1; i <= end; i++) + { + sum += bars.Close(i); + } + + return sum / length; + } + + ///closes ending at , included. + /// Average true range: the simple average of the last + public static double? Atr(BarSeries bars, int length) + { + ArgumentNullException.ThrowIfNull(bars); + var end = bars.Count - 1; + if (length <= 0 || end < length) + { + return null; + } + + var sum = 0d; + for (var i = end - length + 1; i <= end; i++) + { + var previous = bars.Close(i - 1); + var high = bars.High(i); + var low = bars.Low(i); + sum += Math.Max(high - low, Math.Max(Math.Abs(high - previous), Math.Abs(low - previous))); + } + + return sum / length; + } + + ///true ranges, each the largest of + /// high − low, |high − previous close| and |low − previous close|. A plain average, so the value depends only on + /// those bars and not on where the history starts. + /// + /// Wilder's relative strength index on the closes. The smoothing starts from a plain average of the first + /// + public static double? Rsi(BarSeries bars, int length) + { + ArgumentNullException.ThrowIfNull(bars); + if (length <= 0 || bars.Count < length + 1) + { + return null; + } + + var start = Math.Max(0, bars.Count - (RsiWarmUp * length) - 1); + double gain = 0, loss = 0; + for (var i = start + 1; i <= start + length; i++) + { + var change = bars.Close(i) - bars.Close(i - 1); + gain += Math.Max(change, 0); + loss += Math.Max(-change, 0); + } + + gain /= length; + loss /= length; + for (var i = start + length + 1; i < bars.Count; i++) + { + var change = bars.Close(i) - bars.Close(i - 1); + gain = ((gain * (length - 1)) + Math.Max(change, 0)) / length; + loss = ((loss * (length - 1)) + Math.Max(-change, 0)) / length; + } + + if (loss == 0) + { + return gain == 0 ? 50 : 100; + } + + return 100 - (100 / (1 + (gain / loss))); + } + + ///changes of a window of × length bars: older bars weigh less + /// than one part in a million, and the value does not depend on where the history starts. + /// Bars of history the RSI reads, in multiples of its length. + public const int RsiWarmUp = 50; + + ///The last + public static double[]? Returns(BarSeries bars, int count) + { + ArgumentNullException.ThrowIfNull(bars); + if (count <= 0 || bars.Count < count + 1) + { + return null; + } + + var result = new double[count]; + var first = bars.Count - count; + for (var i = 0; i < count; i++) + { + var before = bars.Close(first + i - 1); + result[i] = before > 0 ? (bars.Close(first + i) / before) - 1 : 0; + } + + return result; + } + + ///simple daily returns, oldest first; null when the history is shorter. + /// Annualised volatility of the last + public static double? Volatility(BarSeries bars, int count, int periodsPerYear) + { + var returns = Returns(bars, count); + if (returns is null || returns.Length < 2) + { + return null; + } + + return StandardDeviation(returns) * Math.Sqrt(periodsPerYear); + } + + ///daily returns: sample standard deviation times the + /// square root of the sessions in a year. + /// + /// The return over + public static double? Momentum(BarSeries bars, int length, int skip) + { + ArgumentNullException.ThrowIfNull(bars); + var end = bars.Count - 1 - skip; + var start = end - length; + if (start < 0 || end < 0) + { + return null; + } + + var before = bars.Close(start); + return before > 0 ? (bars.Close(end) / before) - 1 : null; + } + + ///sessions that ends sessions before the last + /// bar: close[t − skip] / close[t − skip − length] − 1. + /// + /// Annualised volatility of a portfolio with the given weights, from the covariance of the last + /// + public static double? PortfolioVolatility(IReadOnlyList<(BarSeries Bars, double Weight)> holdings, int count, int periodsPerYear) + { + ArgumentNullException.ThrowIfNull(holdings); + var series = new List<(Dictionarydaily returns of each instrument, aligned by day. Days missing for an instrument count + /// as no change. Null when no instrument has enough history. + /// Returns, double Weight)>(); + var days = new SortedSet (); + foreach (var (bars, weight) in holdings) + { + if (weight == 0 || bars.Count < count + 1) + { + continue; + } + + var map = new Dictionary (count); + for (var i = bars.Count - count; i < bars.Count; i++) + { + var before = bars.Close(i - 1); + map[bars.Day(i)] = before > 0 ? (bars.Close(i) / before) - 1 : 0; + } + + series.Add((map, weight)); + } + + if (series.Count == 0) + { + return null; + } + + // The common calendar is the last `count` days any of them traded. + foreach (var (map, _) in series) + { + days.UnionWith(map.Keys); + } + + var calendar = days.TakeLast(count).ToList(); + if (calendar.Count < 2) + { + return null; + } + + var portfolio = calendar.Select(d => series.Sum(s => s.Weight * s.Returns.GetValueOrDefault(d))).ToArray(); + return StandardDeviation(portfolio) * Math.Sqrt(periodsPerYear); + } + + /// Sample standard deviation (n − 1). + public static double StandardDeviation(IReadOnlyListvalues) + { + ArgumentNullException.ThrowIfNull(values); + if (values.Count < 2) + { + return 0; + } + + var mean = values.Average(); + var sum = 0d; + foreach (var v in values) + { + sum += (v - mean) * (v - mean); + } + + return Math.Sqrt(sum / (values.Count - 1)); + } + + /// Highest close from + public static double? HighestCloseSince(BarSeries bars, DateOnly from) + { + ArgumentNullException.ThrowIfNull(bars); + double? high = null; + for (var i = bars.Count - 1; i >= 0 && bars.Day(i) >= from; i--) + { + high = Math.Max(high ?? double.MinValue, bars.Close(i)); + } + + return high; + } + + ///to the last bar, both included. Sessions from + public static int SessionsSince(BarSeries bars, DateOnly from) + { + ArgumentNullException.ThrowIfNull(bars); + var n = 0; + for (var i = bars.Count - 1; i >= 0 && bars.Day(i) >= from; i--) + { + n++; + } + + return n; + } + + ///to the last bar, both included. Median of the last + public static double? MedianValue(BarSeries bars, int count, int end) + { + ArgumentNullException.ThrowIfNull(bars); + if (end < count - 1 || end >= bars.Count) + { + return null; + } + + var values = new double[count]; + for (var i = 0; i < count; i++) + { + var k = end - count + 1 + i; + values[i] = bars.Value(k); + } + + Array.Sort(values); + return count % 2 == 1 ? values[count / 2] : (values[(count / 2) - 1] + values[count / 2]) / 2; + } +} diff --git a/src/Anubis/Strategies/Research.cs b/src/Anubis/Strategies/Research.cs index 04dabc0..43a3290 100644 --- a/src/Anubis/Strategies/Research.cs +++ b/src/Anubis/Strategies/Research.cs @@ -143,10 +143,11 @@ public sealed class MovingAverageCrossFamily : IStrategyFamily } } -///traded values (close × volume, or the quote volume when known). The strategies the laboratory can test. The bot's own strategies join with Phase 5. +///The strategies the laboratory can test: the three of the bot first, then the examples. public static class StrategyCatalog { - public static IReadOnlyListAll { get; } = [MovingAverageCrossFamily.Instance, BuyAndHoldFamily.Instance]; + public static IReadOnlyList All { get; } = + [CryptoTrendFamily.Instance, EquityMomentumFamily.Instance, EquityMeanrevFamily.Instance, MovingAverageCrossFamily.Instance, BuyAndHoldFamily.Instance]; public static IStrategyFamily? Find(string id) => All.FirstOrDefault(f => f.Id == id); } diff --git a/src/Anubis/Strategies/Strategy.cs b/src/Anubis/Strategies/Strategy.cs index 24bd73d..992f172 100644 --- a/src/Anubis/Strategies/Strategy.cs +++ b/src/Anubis/Strategies/Strategy.cs @@ -28,6 +28,27 @@ public sealed record Intent(string Symbol, decimal? TargetWeight, string Reason) { public decimal? Stop { get; init; } + /// + /// For a new position: the stop goes this far below the price obtained (a distance in today's prices, such as 3 + /// ATR). Ignored when + public decimal? StopOffset { get; init; } + + ///is given or the position already has a stop. + /// + /// An exit to carry out at this close rather than at the next open: + public bool AtClose { get; init; } + + ///equity_meanrev sells at 15:55 live, + /// which the daily backtest reads as the close (SPEC 8.3). + ///+ /// Reason codes of the correctives and of the risk engine that changed this intent after the strategy (SPEC 5.2): + /// empty when it passed as the strategy proposed it. + /// + public IReadOnlyListAdjustments { get; init; } = []; + + /// The same intent with one more adjustment code. + public Intent Adjusted(string code) => this with { Adjustments = [.. Adjustments, code] }; + public override string ToString() => string.Create(CultureInfo.InvariantCulture, $"{Symbol} {(TargetWeight is { } w ? w.ToString(CultureInfo.InvariantCulture) : "keep")} stop {(Stop is { } s ? s.ToString(CultureInfo.InvariantCulture) : "-")} ({Reason})"); } @@ -94,6 +115,42 @@ public sealed class BarSeries public double Volume(int index) => Bar(index).Volume; + ///Value traded in the session, in the quote currency: the source's own figure, or close × volume. + public double Value(int index) + { + var bar = Bar(index); + return bar.QuoteVolume ?? (bar.Close * bar.Volume); + } + + ///The real close of the session, as traded that day, not adjusted to today. + public double RealClose(int index) => Bar(index).Close; + + ///Index of the last bar on or before + public int IndexThrough(DateOnly day) + { + int lo = 0, hi = Count; + while (lo < hi) + { + var mid = (lo + hi) / 2; + if (_bars[mid].Day <= day) + { + lo = mid + 1; + } + else + { + hi = mid; + } + } + + return lo - 1; + } + + ///; −1 when there is none. The first day of the history; null when there is none. + public DateOnly? FirstDay => Count > 0 ? _bars[0].Day : null; + + ///The day of the last bar; null when there is none. + public DateOnly? LastDay => Count > 0 ? _bars[Count - 1].Day : null; + ///The last public double[] Closes(int length) { @@ -115,8 +172,22 @@ public sealed class BarSeries } } -///closes, oldest first (fewer when the history is shorter). What a strategy may read to choose its instruments for a decision. -public sealed record UniverseContext(DateOnly Day, IReadOnlyListAvailable); +/// +/// What a strategy may read to choose its instruments for a decision: the instruments with data, their bars up to the +/// day and their rules. Live, +public sealed record UniverseContext(DateOnly Day, IReadOnlyListgives the universes chosen and saved "as of a date" (SPEC 6.7). +/// Available) +{ + public Func Bars { get; init; } = _ => BarSeries.Empty; + + public Func Spec { get; init; } = _ => null; + + /// Median spread of the last 30 days in basis points, live only; null in a backtest (no history). + public Func? SpreadBp { get; init; } + + /// The saved universe of a strategy on a date, live; null means "compute it from the bars". + public Func?>? Members { get; init; } +} /// Named numeric parameters of a strategy variant. Values are decimal so a grid is written exactly. public sealed class StrategyParameters @@ -169,8 +240,45 @@ public sealed class StrategyContext( public BarSeries Bars(string symbol) => bars(symbol); public InstrumentSpec? Spec(string symbol) => spec(symbol); + + ///+ /// The next session of the market calendar after + public DateOnly? NextSession { get; init; } + + ///. Calendars are published in advance, so this + /// is not looking ahead: equity_momentum uses it to find the last session before a new week. + ///+ /// The reference equity of SPEC 9.2: capital entrusted on every broker plus the strategies' results, which does + /// not move when a strategy changes stage. In the backtest of one strategy: its equity divided by its share of + /// the total. Defaults to the strategy's equity. + /// + public decimal ReferenceEquity + { + get => _reference ?? Portfolio.Equity; + init => _reference = value; + } + + private readonly decimal? _reference; + + ///Sessions in a year for this market: 365 for crypto, 252 for stocks. + public int PeriodsPerYear { get; init; } = 365; + + ///Next earnings date of a stock, live and when the calendar has it; null in a backtest (SPEC 8.3). + public Func? NextEarnings { get; init; } + + /// A restriction from the news on the instrument (SPEC 10.5, Phase 7); null in a backtest. + public Func? Restricted { get; init; } + + /// + /// The strategy's equity at each earlier close, up to and including this one: what the risk limits of SPEC 9.2 + /// measure losses and the fall from the high on. + /// + public IReadOnlyListHistory { get; init; } = []; } +/// The equity at a close and the part of it in positions. +public sealed record EquityMark(DateOnly Day, decimal Equity, decimal Invested); + ///A trading strategy (SPEC 5.3): a function of the data up to "now" and of its own book, nothing else. public interface IStrategy { diff --git a/src/Anubis/Trading/Decisions.cs b/src/Anubis/Trading/Decisions.cs new file mode 100644 index 0000000..9473730 --- /dev/null +++ b/src/Anubis/Trading/Decisions.cs @@ -0,0 +1,74 @@ +using System.Text.Json; +using Anubis.Core; +using Anubis.Db; + +namespace Anubis.Trading; + +///Stages of a decision (SPEC 5.2), in the order they are crossed. +public static class DecisionStages +{ + public const string Strategy = "strategy"; + public const string Correctives = "correctives"; + public const string Sizing = "sizing"; + public const string Risk = "risk"; + public const string Order = "order"; + + ///The one-step comparison of SPEC 12.3: live intents against the backtest restarted from the recorded state. + public const string OneStep = "one_step"; +} + +public static class DecisionOutcomes +{ + public const string Proposed = "proposed"; + public const string Passed = "passed"; + public const string Reduced = "reduced"; + public const string Refused = "refused"; + public const string Same = "same"; + public const string Different = "different"; +} + +///A row of the decisions table: a stage, its outcome, its reason codes and the numbers it used. +public sealed record DecisionRow(Guid DecisionId, string Strategy, Guid? AccountId, string? Symbol, string Stage, string Outcome, IReadOnlyListReasons, + IReadOnlyDictionary ? Data, DateTimeOffset At); + +/// +/// The record of every decision (SPEC 5.2): each stage writes one row with reason codes and values, never free text. +/// The diary and the "why" card are built from these rows with fixed templates. +/// +public sealed class DecisionLog(Database db, IClock clock) +{ + public Task WriteAsync(DecisionRow row, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(row); + return db.WriteAsync(s => WriteAsync(s, clock, row, cancellationToken), cancellationToken); + } + + public static TaskWriteAsync(DbSession s, IClock clock, DecisionRow row, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(s); + ArgumentNullException.ThrowIfNull(clock); + ArgumentNullException.ThrowIfNull(row); + return s.ExecuteAsync( + "INSERT INTO decisions (id, decision_id, strategy, account_id, symbol, stage, outcome, reasons, data, created_at) VALUES (@id, @d, @s, @a, @sym, @st, @o, @r, @data, @t)", + cancellationToken, ("id", Ids.NewId(clock)), ("d", row.DecisionId), ("s", row.Strategy), ("a", row.AccountId), ("sym", row.Symbol), ("st", row.Stage), ("o", row.Outcome), + ("r", new DbJson(JsonSerializer.Serialize(row.Reasons))), ("data", row.Data is null ? null : new DbJson(JsonSerializer.Serialize(row.Data))), ("t", row.At)); + } + + /// Every stage of one decision, in order. + public Task> OfAsync(Guid decisionId, CancellationToken cancellationToken) => + db.ReadAsync(s => s.QueryAsync("SELECT decision_id, strategy, account_id, symbol, stage, outcome, reasons, data, created_at FROM decisions WHERE decision_id = @d ORDER BY created_at, id", + Read, ("d", decisionId)), cancellationToken); + + ///
The latest rows of a strategy, or of every strategy, newest first. + public Task> RecentAsync(string? strategy, int limit, CancellationToken cancellationToken) => + db.ReadAsync(s => s.QueryAsync( + "SELECT decision_id, strategy, account_id, symbol, stage, outcome, reasons, data, created_at FROM decisions" + (strategy is null ? "" : " WHERE strategy = @s") + + " ORDER BY created_at DESC, id DESC LIMIT @n", Read, strategy is null ? [("n", limit)] : [("s", strategy), ("n", limit)]), cancellationToken); + + private static DecisionRow Read(DbRow r) + { + var data = r.TextOrNull("data") is { } json ? JsonSerializer.Deserialize
>(json) : null; + return new DecisionRow(r.Id("decision_id"), r.Text("strategy"), r.IdOrNull("account_id"), r.TextOrNull("symbol"), r.Text("stage"), r.Text("outcome"), + JsonSerializer.Deserialize >(r.Text("reasons")) ?? [], data, r.Moment("created_at")); + } +} diff --git a/src/Anubis/Trading/Equity.cs b/src/Anubis/Trading/Equity.cs index 370de17..768dbbf 100644 --- a/src/Anubis/Trading/Equity.cs +++ b/src/Anubis/Trading/Equity.cs @@ -73,7 +73,10 @@ public sealed class EquityBook(Database db, IClock clock, Ledger ledger, FxStore } } - foreach (var group in shots.GroupBy(s => s.AccountId)) + // The simulated twin of a strategy with real money is photographed, but stays out of the totals (SPEC 12.3). + var twins = (await db.ReadAsync(s => s.QueryAsync("SELECT strategy, account_id FROM strategy_state WHERE stage IN ('reduced', 'real') AND account_id IS NOT NULL", + r => (Strategy: r.Text("strategy"), Account: r.Id("account_id"))), cancellationToken).ConfigureAwait(false)).ToHashSet(); + foreach (var group in shots.Where(s => !twins.Contains((s.Strategy!, s.AccountId!.Value))).GroupBy(s => s.AccountId)) { var first = group.First(); shots.Add(new Shot("account", first.World, first.AccountId, null, first.Currency, group.Sum(s => s.Equity), group.Sum(s => s.Cash), group.Sum(s => s.Invested), diff --git a/src/Anubis/Trading/OrderManager.cs b/src/Anubis/Trading/OrderManager.cs index a72cece..ae01c7f 100644 --- a/src/Anubis/Trading/OrderManager.cs +++ b/src/Anubis/Trading/OrderManager.cs @@ -15,6 +15,14 @@ public sealed record TradeIntent(Guid InstrumentId, string Strategy, OrderSide S public decimal? StopLevel { get; init; } } +///
What the risk engine says of an intent: the quantity allowed (never more than asked), or why it is refused. +public sealed record GateResult(decimal Quantity, string? Refusal, IReadOnlyListReasons) +{ + public static GateResult Pass(decimal quantity) => new(quantity, null, []); + + public static GateResult Refuse(string reason) => new(0m, reason, [reason]); +} + /// The account an order manager works on. public sealed record AccountContext(Guid AccountId, string Name, string Broker, string Environment, string Currency); @@ -127,6 +135,21 @@ public sealed partial class OrderManager : IDisposable ///Called after new fills are recorded: the equity is photographed at every execution (SPEC 7.5). public Func? AfterFills { get; init; } + /// + /// The risk engine (SPEC 9): every intent crosses it before it becomes an execution, and it may refuse it or + /// make it smaller. Protection always passes. + /// + public Func>? Gate { get; init; } + + /// + /// The permission of SPEC 12.4 for a real account, asked again right before every order leaves. Without it an + /// order manager on a real account sends nothing but protection: it fails closed. + /// + public Func>? LivePermit { get; init; } + + /// The technical check of a purchase's limit against the last valid price (SPEC 9.2): a reason refuses it. + public Func? PurchasePriceCheck { get; init; } + public AccountContext Account => _account; public IBrokerAccount Broker => _broker; @@ -155,6 +178,29 @@ public sealed partial class OrderManager : IDisposable return (null, OrderReasons.PrudentMode); } + if (await LiveRefusalAsync(intent, cancellationToken).ConfigureAwait(false) is { } live) + { + return (null, live); + } + + if (Gate is not null && intent.Purpose != OrderPurpose.Protective) + { + var verdict = await Gate(intent, _account, cancellationToken).ConfigureAwait(false); + if (verdict.Refusal is { } refusal) + { + return (null, refusal); + } + + if (verdict.Quantity < intent.Quantity) + { + intent = intent with { Quantity = verdict.Quantity }; + if (intent.Quantity <= 0m) + { + return (null, OrderReasons.ZeroQuantity); + } + } + } + var id = Ids.NewId(_clock); var now = _clock.UtcNow; await _db.WriteAsync(s => s.ExecuteAsync( @@ -327,6 +373,55 @@ public sealed partial class OrderManager : IDisposable _db.ReadAsync >(async s => (await s.QueryAsync(OrderSelect + " WHERE account_id = @a AND status IN ('submitted', 'partially_filled')", ReadOrder, ("a", _account.AccountId)).ConfigureAwait(false)).Select(o => (o.ClientOrderId, o.InstrumentId, o.Purpose)).ToList(), cancellationToken); + /// + /// Cancels the executions under way, except protective sales (SPEC 9.3, "Ferma tutto"): the open order of each is + /// canceled with the broker, and the stops it had removed come back at once for the quantity held. + /// + public async TaskCancelWorkingAsync(string reason, Func ? strategy = null, CancellationToken cancellationToken = default) + { + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + var count = 0; + foreach (var exec in await WorkingAsync(cancellationToken).ConfigureAwait(false)) + { + if (exec.Purpose == OrderPurpose.Protective || (strategy is not null && !strategy(exec.Strategy))) + { + continue; + } + + var instrument = await _instruments(exec.InstrumentId, cancellationToken).ConfigureAwait(false) + ?? throw new InvalidOperationException("Unknown instrument " + exec.InstrumentId); + var orders = await ExecutionOrdersAsync(exec.Id, cancellationToken).ConfigureAwait(false); + if (orders.LastOrDefault() is { } current && !OrderStates.IsFinal(current.Status)) + { + await CancelAndReadAsync(current, instrument, reason, cancellationToken).ConfigureAwait(false); + } + + await SyncFillsCoreAsync(cancellationToken).ConfigureAwait(false); + await FinishAsync(exec, ExecutionStates.Canceled, reason, instrument, cancellationToken).ConfigureAwait(false); + count++; + } + + return count; + } + finally + { + _gate.Release(); + } + } + + // A real account sends only what the procedure of SPEC 12.4 allows; protection of what the bot holds always goes. + private async Task LiveRefusalAsync(TradeIntent intent, CancellationToken cancellationToken) + { + if (_account.Environment != TradingEnvironments.Live || intent.Purpose == OrderPurpose.Protective) + { + return null; + } + + return LivePermit is null ? Risk.RiskReasons.LiveNotConfirmed : await LivePermit(intent, _account, cancellationToken).ConfigureAwait(false); + } + public Task IsPrudentAsync(CancellationToken cancellationToken) => _db.ReadAsync(async s => await s.FirstOrDefaultAsync("SELECT mode FROM account_status WHERE account_id = @a", r => r.Text("mode"), ("a", _account.AccountId)).ConfigureAwait(false) == AccountModes.Prudent, cancellationToken); @@ -500,6 +595,19 @@ public sealed partial class OrderManager : IDisposable return; } + // Asked again right before the order leaves: a revocation or a demotion meanwhile stops it here. + if (await LiveRefusalAsync(new TradeIntent(exec.InstrumentId, exec.Strategy, exec.Side, remaining, exec.Purpose, Guid.Empty), cancellationToken).ConfigureAwait(false) is { } live) + { + await FinishAsync(exec, ExecutionStates.Canceled, live, instrument, cancellationToken).ConfigureAwait(false); + return; + } + + if (exec.Side == OrderSide.Buy && rounded.LimitPrice is { } price && PurchasePriceCheck?.Invoke(price, quote) is { } gap) + { + await FinishAsync(exec, ExecutionStates.Canceled, gap, instrument, cancellationToken).ConfigureAwait(false); + return; + } + var sequence = exec.Sequence + 1; var clientId = ClientOrderIds.Build(_installation, _account.Environment, exec.Strategy, exec.Purpose, exec.Key, sequence); var now = _clock.UtcNow; diff --git a/src/Anubis/Trading/RiskEngine.cs b/src/Anubis/Trading/RiskEngine.cs new file mode 100644 index 0000000..a914251 --- /dev/null +++ b/src/Anubis/Trading/RiskEngine.cs @@ -0,0 +1,617 @@ +using System.Text.Json; +using Anubis.Core; +using Anubis.Data; +using Anubis.Db; +using Anubis.Risk; + +namespace Anubis.Trading; + +/// A world as the risk engine sees it now: what it remembers, the three measures, the multiplier on purchases. +public sealed record WorldRisk(string World, RiskMonitorState State, RiskMeasures Measures, decimal Multiplier, bool EntriesBlocked); + +///Exposure of the bot in euro, from the ledgers: equity and invested per world, crypto everywhere. Twins are left out. +public sealed record RiskExposure(decimal SimulatedEquity, decimal SimulatedInvested, decimal RealEquity, decimal RealInvested, decimal Crypto) +{ + public decimal Equity(string world) => world == Worlds.Real ? RealEquity : SimulatedEquity; + + public decimal Invested(string world) => world == Worlds.Real ? RealInvested : SimulatedInvested; +} + +///What the bot as a whole remembers: a "stop and close all" still waiting for markets to open. +public sealed record BotRiskState +{ + public bool CloseAll { get; init; } + + public DateTimeOffset? CloseAllSince { get; init; } +} + +///+/// The risk engine (SPEC 9): every intent of a strategy crosses it before it becomes an order, and nothing gets +/// around it. It refuses or shrinks, never enlarges (9.1 point 6). It watches the losses of each world, trips the +/// switch of the world that crossed a limit (9.2), stops the bot on an anomaly of orders per minute or on the file +/// +public sealed class RiskEngine(Database db, IClock clock, Ledger ledger, StageBook stages, SettingsStore settings, FxStore fx, + Func/data/STOP , and restarts only on the user's confirmation (9.3). Protection always passes. +///> instruments, Func > quotes) +{ + public const string BotRow = "bot"; + public const string PdtReason = "pdt_guard"; + public const string UnknownInstrument = "unknown_instrument"; + public const string NoRate = "no_fx_rate"; + public const int PdtMaxDayTrades = 3; + + private static readonly JsonSerializerOptions Json = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower }; + private static readonly TimeZoneInfo NewYork = TimeZoneInfo.FindSystemTimeZoneById("America/New_York"); + + /// The file that stops the bot (SPEC 9.3): + public string? StopFile { get; init; } + + ////data/STOP in Docker, the data folder on desktop.The clock skew measured with a broker, when known (SPEC 9.2): beyond the limit no new entries. + public Func? ClockSkew { get; init; } + + public bool StopRequested => StopFile is { } path && File.Exists(path); + + /// The gate of the order manager: the verdict on an intent, written to the decisions table (SPEC 5.2). + public async TaskGateAsync(TradeIntent intent, AccountContext account, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(intent); + ArgumentNullException.ThrowIfNull(account); + if (intent.Purpose is OrderPurpose.Protective or OrderPurpose.Stop) + { + return GateResult.Pass(intent.Quantity); + } + + var (result, data) = await DecideAsync(intent, account, cancellationToken).ConfigureAwait(false); + var outcome = result.Refusal is not null ? DecisionOutcomes.Refused : result.Quantity < intent.Quantity ? DecisionOutcomes.Reduced : DecisionOutcomes.Passed; + var instrument = await instruments(intent.InstrumentId, cancellationToken).ConfigureAwait(false); + data["asked"] = intent.Quantity; + data["allowed"] = result.Quantity; + await db.WriteAsync(s => DecisionLog.WriteAsync(s, clock, new DecisionRow(intent.DecisionId, intent.Strategy, account.AccountId, instrument?.Symbol, DecisionStages.Risk, outcome, + result.Reasons, data, clock.UtcNow), cancellationToken), cancellationToken).ConfigureAwait(false); + return result; + } + + private async Task<(GateResult Result, Dictionary Data)> DecideAsync(TradeIntent intent, AccountContext account, CancellationToken cancellationToken) + { + var data = new Dictionary (StringComparer.Ordinal); + var now = clock.UtcNow; + var botState = (await settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value; + if (botState == "stopped" || StopRequested) + { + return (GateResult.Refuse(RiskReasons.BotStopped), data); + } + + var stage = await stages.GetAsync(intent.Strategy, cancellationToken).ConfigureAwait(false); + var world = WorldOf(account, stage); + data["world"] = world; + var risk = await WorldAsync(world, cancellationToken).ConfigureAwait(false); + if (risk.State.Tripped) + { + return (GateResult.Refuse(RiskReasons.SwitchTripped), data); + } + + if (await instruments(intent.InstrumentId, cancellationToken).ConfigureAwait(false) is not { } instrument) + { + return (GateResult.Refuse(UnknownInstrument), data); + } + + var position = await ledger.PositionAsync(account.AccountId, intent.InstrumentId, intent.Strategy, cancellationToken).ConfigureAwait(false); + var held = position?.Quantity ?? 0m; + data["held"] = held; + var limits = await RiskSettings.LoadAsync(settings, cancellationToken).ConfigureAwait(false); + var pdt = account.Broker == Venues.Alpaca && await RiskSettings.PdtGuardAsync(settings, cancellationToken).ConfigureAwait(false); + if (intent.Side == OrderSide.Sell) + { + // Only what this strategy bought, never more than it holds (SPEC 9.1 points 1 and 3). + if (held <= 0m) + { + var others = (await ledger.PositionsAsync(account.AccountId, cancellationToken).ConfigureAwait(false)).Any(p => p.InstrumentId == intent.InstrumentId); + return (GateResult.Refuse(others ? RiskReasons.OwnedByOther : RiskReasons.NotOwned), data); + } + + if (pdt && intent.Strategy == StrategyNames.EquityMeanrev && NewYorkDay(position!.OpenedAt) == NewYorkDay(now)) + { + // With the guard on, mean reversion never leaves on the day it entered: the stop protects it (SPEC 9.2). + return (GateResult.Refuse(PdtReason), data); + } + + return intent.Quantity > held ? (new GateResult(held, null, [RiskReasons.NoShortSelling]), data) : (GateResult.Pass(intent.Quantity), data); + } + + if (intent.Purpose != OrderPurpose.Entry) + { + return (GateResult.Refuse(RiskReasons.NoShortSelling), data); + } + + if (botState == "paused") + { + return (GateResult.Refuse(RiskReasons.BotPaused), data); + } + + if (stage?.Stage == StrategyStages.Observation) + { + 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); + } + + var quote = await quotes(instrument.Symbol, cancellationToken).ConfigureAwait(false); + if (RiskRules.TechnicalRefusal(now, quote?.At, quote?.Mid, null, ClockSkew?.Invoke(account.Broker), limits) is { } technical) + { + return (GateResult.Refuse(technical), data); + } + + if (pdt && await PdtRoomAsync(account.AccountId, cancellationToken).ConfigureAwait(false) <= 0) + { + return (GateResult.Refuse(PdtReason), data); + } + + var rate = account.Currency == "EUR" ? 1m : await UsdRateAsync(cancellationToken).ConfigureAwait(false); + if (rate is not > 0m) + { + return (GateResult.Refuse(NoRate), data); + } + + var exposure = await ExposureAsync(cancellationToken).ConfigureAwait(false); + var reference = await ReferenceAsync(cancellationToken).ConfigureAwait(false); + + // A strategy in reduced real works on a quarter: its limits apply on a quarter of the reference (SPEC 9.2). + var quarter = stage?.Stage == StrategyStages.Reduced && account.Environment == TradingEnvironments.Live ? StrategyStages.ReducedShare : 1m; + var price = quote!.Ask > 0m ? quote.Ask : quote.Mid; + var request = new PurchaseRequest + { + Price = price, + Held = held, + Wanted = intent.Quantity, + Stop = intent.StopLevel ?? position?.StopPrice, + Multiplier = risk.Multiplier, + WorldEquity = exposure.Equity(world) * rate.Value, + WorldInvested = exposure.Invested(world) * rate.Value, + Reference = reference * rate.Value * quarter, + IsCrypto = instrument.IsCrypto, + CryptoValue = exposure.Crypto * rate.Value * quarter, + }; + data["price"] = price; + data["multiplier"] = risk.Multiplier; + data["reference"] = request.Reference; + data["world_equity"] = request.WorldEquity; + var size = RiskRules.SizePurchase(request, limits); + 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). 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; + data["reserved"] = cash - available; + if (quantity * price * highest > available) + { + quantity = Math.Max(0m, available / (price * highest)); + reasons.Add(RiskReasons.NoLeverage); + } + + quantity = Math.Min(quantity, intent.Quantity); + if (quantity <= 0m) + { + var reason = reasons.Count > 0 ? reasons[^1] : RiskReasons.Reduction; + return (new GateResult(0m, reason, reasons.Count > 0 ? reasons : [reason]), data); + } + + return (new GateResult(quantity, null, reasons), data); + } + + /// + /// The world an order counts in (SPEC 7.1, 12.3): real accounts in the real world, the rest in simulation; the + /// twin of a strategy with real money follows the blocks of the real strategy. + /// + public static string WorldOf(AccountContext account, StrategyStage? stage) + { + ArgumentNullException.ThrowIfNull(account); + if (account.Environment == TradingEnvironments.Live) + { + return Worlds.Real; + } + + return stage is { HasTwin: true } && stage.AccountId == account.AccountId ? Worlds.Real : Worlds.Simulated; + } + + ///The state of a world with its measures now. + public async TaskWorldAsync(string world, CancellationToken cancellationToken) + { + var state = await LoadAsync (world, cancellationToken).ConfigureAwait(false) ?? RiskMonitorState.Initial; + var limits = await RiskSettings.LoadAsync(settings, cancellationToken).ConfigureAwait(false); + var now = clock.UtcNow; + var measures = RiskMeasures.From(await SeriesAsync(world, cancellationToken).ConfigureAwait(false), now, state.PeakFrom, state.Peak); + return new WorldRisk(world, state, measures, RiskMonitor.Multiplier(state, measures, now, limits), RiskMonitor.EntriesBlocked(state, now)); + } + + /// + /// The periodic check (SPEC 9.2, 9.3): the measures of each world with its blocks, warnings and switch; the + /// orders per minute of each account; the file + public async Task/data/STOP ; a "stop and close all" waiting for the open. + ///> CheckAsync(IReadOnlyCollection managers, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(managers); + var alerts = new List (); + var now = clock.UtcNow; + var limits = await RiskSettings.LoadAsync(settings, cancellationToken).ConfigureAwait(false); + foreach (var world in new[] { Worlds.Simulated, Worlds.Real }) + { + var state = await LoadAsync (world, cancellationToken).ConfigureAwait(false) ?? RiskMonitorState.Initial with { PeakFrom = now }; + var series = await SeriesAsync(world, cancellationToken).ConfigureAwait(false); + if (series.Count == 0) + { + continue; + } + + var reading = RiskMonitor.Step(state, RiskMeasures.From(series, now, state.PeakFrom, state.Peak), now, limits); + await SaveAsync(world, reading.State, cancellationToken).ConfigureAwait(false); + foreach (var alert in reading.Alerts) + { + await RecordAsync(world, alert.Kind, alert.Severity, alert.Message, new { alert.Value, alert.Threshold }, cancellationToken).ConfigureAwait(false); + } + + if (reading.State.Tripped && !state.Tripped) + { + // The switch stops only the world that crossed the limit (SPEC 9.2). + await CancelAsync(managers, world, "switch_tripped", cancellationToken).ConfigureAwait(false); + } + + alerts.AddRange(reading.Alerts); + } + + var from = now - TimeSpan.FromMinutes(1); + var sent = await db.ReadAsync(s => s.QueryAsync( + "SELECT account_id, COUNT(*) AS n FROM orders WHERE submitted_at >= @f AND purpose IN ('entry', 'exit') GROUP BY account_id", + r => (Account: r.Id("account_id"), Count: r.Number("n")), ("f", from)), cancellationToken).ConfigureAwait(false); + if (sent.FirstOrDefault(x => x.Count >= limits.OrdersPerMinute) is { Count: > 0 } burst) + { + var message = $"{burst.Count} ordini inviati in un minuto su un conto, oltre il limite di {limits.OrdersPerMinute}: fermo il bot, può essere un guasto."; + await StopAllAsync(managers, "automatico", RiskReasons.OrdersPerMinute, message, cancellationToken).ConfigureAwait(false); + alerts.Add(new RiskAlert(RiskReasons.OrdersPerMinute, RiskSeverities.Critical, message, burst.Count, limits.OrdersPerMinute)); + } + + if (StopRequested && (await settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value != "stopped") + { + await StopAllAsync(managers, "file STOP", "stop_file", "Ho trovato il file STOP nella cartella dei dati: fermo tutto. Per ripartire toglilo e conferma dall'interfaccia.", + cancellationToken).ConfigureAwait(false); + } + + await ContinueCloseAllAsync(managers, cancellationToken).ConfigureAwait(false); + return alerts; + } + + /// + /// "Ferma tutto" (SPEC 9.3): no new entries and no sales of the strategies, the orders under way canceled except + /// protection; the stops stay and are put back where a canceled sale had removed them. + /// + public async Task StopAllAsync(IReadOnlyCollectionmanagers, string by, string reason, string message, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(managers); + await settings.SetAsync(SettingsStore.BotState.Key, "stopped", 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); + } + } + + /// + /// "Ferma e chiudi tutte le posizioni" (SPEC 9.3), after the user's confirmation: everything stops, then + /// everything the bot holds is sold at market. A position's stop goes only when its sale leaves; what belongs to a + /// closed market leaves at the open and keeps its stop until then. + /// + public async Task CloseAllAsync(IReadOnlyCollectionmanagers, string by, CancellationToken cancellationToken) + { + await StopAllAsync(managers, by, "close_all", "Fermo tutto e vendo a mercato ogni posizione del bot: ciò che è su un mercato chiuso parte all'apertura e intanto tiene il suo stop.", + cancellationToken).ConfigureAwait(false); + await SaveAsync(BotRow, new BotRiskState { CloseAll = true, CloseAllSince = clock.UtcNow }, cancellationToken).ConfigureAwait(false); + await ContinueCloseAllAsync(managers, cancellationToken).ConfigureAwait(false); + } + + /// Sends the sales of a "stop and close all" whose market is now open. Returns how many positions are still waiting. + public async TaskContinueCloseAllAsync(IReadOnlyCollection managers, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(managers); + if (await LoadAsync (BotRow, cancellationToken).ConfigureAwait(false) is not { CloseAll: true }) + { + return 0; + } + + var waiting = 0; + foreach (var manager in managers) + { + foreach (var position in await ledger.PositionsAsync(manager.Account.AccountId, cancellationToken).ConfigureAwait(false)) + { + if (await instruments(position.InstrumentId, cancellationToken).ConfigureAwait(false) is not { } instrument) + { + continue; + } + + if (manager.MarketOpen is not null && !await manager.MarketOpen(instrument, cancellationToken).ConfigureAwait(false)) + { + waiting++; + continue; + } + + var selling = await db.ReadAsync(s => s.CountAsync( + "SELECT COUNT(*) FROM executions WHERE account_id = @a AND instrument_id = @i AND strategy = @s AND status = @w AND side = 'sell'", + ("a", position.AccountId), ("i", position.InstrumentId), ("s", position.Strategy), ("w", ExecutionStates.Working)), cancellationToken).ConfigureAwait(false); + if (selling == 0) + { + await manager.SubmitAsync(new TradeIntent(position.InstrumentId, position.Strategy, OrderSide.Sell, position.Quantity, OrderPurpose.Protective, Ids.NewId(clock)), + cancellationToken).ConfigureAwait(false); + } + } + } + + if (waiting == 0 && (await ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false)).Count == 0) + { + await SaveAsync(BotRow, new BotRiskState(), cancellationToken).ConfigureAwait(false); + } + + return waiting; + } + + /// + /// The restart after "Ferma tutto" or a tripped switch, confirmed by the user in the interface (SPEC 9.3): never by + /// itself, never from Telegram. When the trip came from the fall from the high, the high starts again from now. + /// + public async Task RestartAsync(string by, CancellationToken cancellationToken) + { + if (StopRequested) + { + throw new InvalidOperationException("Il file STOP è ancora nella cartella dei dati: toglilo prima di ripartire."); + } + + var now = clock.UtcNow; + foreach (var world in new[] { Worlds.Simulated, Worlds.Real }) + { + if (await LoadAsync(world, cancellationToken).ConfigureAwait(false) is { Tripped: true } state) + { + await SaveAsync(world, RiskMonitor.Restart(state, now), cancellationToken).ConfigureAwait(false); + await RecordAsync(world, "restart", RiskSeverities.Info, "Ripartenza confermata: il massimo di riferimento riparte dal patrimonio di adesso.", new { by }, cancellationToken) + .ConfigureAwait(false); + } + } + + await SaveAsync(BotRow, new BotRiskState(), 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); + } + } + + /// True when the switch of at least one world tripped and waits for the user (SPEC 9.3). + public async TaskAnyTrippedAsync(CancellationToken cancellationToken) + { + foreach (var world in new[] { Worlds.Simulated, Worlds.Real }) + { + if (await LoadAsync (world, cancellationToken).ConfigureAwait(false) is { Tripped: true }) + { + return true; + } + } + + return false; + } + + /// + /// Exposure from the ledgers, in euro (SPEC 9.2). The twin of a strategy with real money is left out of every + /// total (SPEC 12.3). + /// + public async TaskExposureAsync(CancellationToken cancellationToken) + { + var rate = await UsdRateAsync(cancellationToken).ConfigureAwait(false); + var accounts = await AccountsAsync(cancellationToken).ConfigureAwait(false); + var twins = await TwinsAsync(cancellationToken).ConfigureAwait(false); + decimal Eur(Guid account, decimal value) => accounts.TryGetValue(account, out var a) && a.Currency == "USD" ? (rate is > 0m ? value / rate.Value : 0m) : value; + decimal simEquity = 0m, simInvested = 0m, realEquity = 0m, realInvested = 0m; + foreach (var e in await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false)) + { + if (twins.Contains((e.AccountId, e.Strategy)) || !accounts.TryGetValue(e.AccountId, out var account)) + { + continue; + } + + if (account.Environment == TradingEnvironments.Live) + { + realEquity += Eur(e.AccountId, e.Equity); + realInvested += Eur(e.AccountId, e.Invested); + } + else + { + simEquity += Eur(e.AccountId, e.Equity); + simInvested += Eur(e.AccountId, e.Invested); + } + } + + var crypto = 0m; + foreach (var p in await ledger.PositionsAsync(null, cancellationToken).ConfigureAwait(false)) + { + if (!twins.Contains((p.AccountId, p.Strategy)) && await instruments(p.InstrumentId, cancellationToken).ConfigureAwait(false) is { IsCrypto: true }) + { + crypto += Eur(p.AccountId, p.Value); + } + } + + return new RiskExposure(simEquity, simInvested, realEquity, realInvested, crypto); + } + + /// + /// The reference equity of SPEC 9.2, in euro: the capital entrusted plus what the strategies produced, twins left + /// out. The ledger of a strategy in reduced real counts four times; results of ledgers it left stay in. While + /// everything is in simulation it is the equity. + /// + public async TaskReferenceAsync(CancellationToken cancellationToken) + { + var rate = await UsdRateAsync(cancellationToken).ConfigureAwait(false); + var accounts = await AccountsAsync(cancellationToken).ConfigureAwait(false); + var all = await stages.AllAsync(cancellationToken).ConfigureAwait(false); + var counted = new HashSet<(Guid, string)>(); + var total = 0m; + var equities = await ledger.EquitiesAsync(cancellationToken).ConfigureAwait(false); + decimal Eur(Guid account, decimal value) => accounts.TryGetValue(account, out var a) && a.Currency == "USD" ? (rate is > 0m ? value / rate.Value : 0m) : value; + foreach (var stage in all) + { + var carried = await CarriedAsync(stage.Strategy, cancellationToken).ConfigureAwait(false); + 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 - carried.Baseline(account)) * factor; + counted.Add((account, stage.Strategy)); + } + + // The twin's ledger and an exit-only real ledger are not part of the reference beyond what was carried. + if (stage.AccountId is { } sim) + { + counted.Add((sim, stage.Strategy)); + } + + if (stage.LiveAccountId is { } live) + { + counted.Add((live, stage.Strategy)); + } + } + + // Ledgers of strategies without a stage row (examples, tests) count as they are. + total += equities.Where(e => !counted.Contains((e.AccountId, e.Strategy))).Sum(e => Eur(e.AccountId, e.Equity)); + return total; + } + + /// What the bot as a whole remembers: a "stop and close all" still waiting for the open. + public async TaskBotAsync(CancellationToken cancellationToken) => + await LoadAsync (BotRow, cancellationToken).ConfigureAwait(false) ?? new BotRiskState(); + + /// The risk events, newest first, for the Rischio screen. + public Task> EventsAsync(int limit, CancellationToken cancellationToken) => + db.ReadAsync(s => s.QueryAsync("SELECT occurred_at, kind, severity, message, world FROM risk_events ORDER BY occurred_at DESC, id DESC LIMIT @n", + r => (r.Moment("occurred_at"), r.Text("kind"), r.Text("severity"), r.Text("message"), r.TextOrNull("world")), ("n", limit)), cancellationToken); + + ///
+ /// Room for new stock positions today with the day-trade guard on (SPEC 9.2): three minus the day trades of the + /// last five sessions minus the positions opened today, so not even a day of stops goes beyond. + /// + public async TaskPdtRoomAsync(Guid accountId, CancellationToken cancellationToken) + { + var now = clock.UtcNow; + var fills = await db.ReadAsync(s => s.QueryAsync("SELECT instrument_id, side, executed_at FROM fills WHERE account_id = @a AND executed_at >= @f AND reverses_id IS NULL", + r => (Instrument: r.Id("instrument_id"), Side: r.Text("side"), At: r.Moment("executed_at")), ("a", accountId), ("f", now - TimeSpan.FromDays(8))), cancellationToken) + .ConfigureAwait(false); + + // Five sessions back, counted on weekdays; a holiday only makes the window longer, which is the prudent side. + var today = NewYorkDay(now); + var start = today; + for (var sessions = 1; sessions < 5;) + { + start = start.AddDays(-1); + if (start.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday)) + { + sessions++; + } + } + + var dayTrades = fills.Where(f => NewYorkDay(f.At) >= start).GroupBy(f => (f.Instrument, Day: NewYorkDay(f.At))) + .Count(g => g.Any(f => f.Side == "buy") && g.Any(f => f.Side == "sell")); + var openedToday = fills.Where(f => f.Side == "buy" && NewYorkDay(f.At) == today).Select(f => f.Instrument).Distinct().Count(); + var buying = await db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM executions WHERE account_id = @a AND side = 'buy' AND status = @w", + ("a", accountId), ("w", ExecutionStates.Working)), cancellationToken).ConfigureAwait(false); + return PdtMaxDayTrades - dayTrades - openedToday - (int)buying; + } + + private static DateOnly NewYorkDay(DateTimeOffset at) => DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(at, NewYork).DateTime); + + private async Task CancelAsync(IReadOnlyCollection managers, string world, string reason, CancellationToken cancellationToken) + { + var all = await stages.AllAsync(cancellationToken).ConfigureAwait(false); + foreach (var manager in managers) + { + bool InWorld(string strategy) => WorldOf(manager.Account, all.FirstOrDefault(s => s.Strategy == strategy)) == world; + await manager.CancelWorkingAsync(reason, InWorld, cancellationToken).ConfigureAwait(false); + } + } + + private Task > SeriesAsync(string world, CancellationToken cancellationToken) => + db.ReadAsync(s => s.QueryAsync("SELECT taken_at, twr_index FROM equity_snapshots WHERE scope = 'total' AND world = @w AND taken_at >= @f AND twr_index IS NOT NULL ORDER BY taken_at, id", + r => new IndexPoint(r.Moment("taken_at"), r.Money("twr_index")), ("w", world), ("f", clock.UtcNow - TimeSpan.FromDays(8))), cancellationToken); + + private async Task
> AccountsAsync(CancellationToken cancellationToken) => + (await db.ReadAsync(s => s.QueryAsync("SELECT id, environment, base_currency FROM accounts", r => (Id: r.Id("id"), Environment: r.Text("environment"), Currency: r.Text("base_currency"))), + cancellationToken).ConfigureAwait(false)).ToDictionary(a => a.Id, a => (a.Environment, a.Currency)); + + private async Task > 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 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 UsdRateAsync(CancellationToken cancellationToken) => + (await fx.LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false))?.Rate; + + private async Task LoadAsync (string world, CancellationToken cancellationToken) + where T : class + { + var json = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT state FROM risk_state WHERE world = @w", r => r.Text("state"), ("w", world)), cancellationToken).ConfigureAwait(false); + return json is null ? null : JsonSerializer.Deserialize (json, Json); + } + + private Task SaveAsync (string world, T state, CancellationToken cancellationToken) => + db.WriteAsync(async s => + { + var json = new DbJson(JsonSerializer.Serialize(state, Json)); + var now = clock.UtcNow; + if (await s.ExecuteAsync("UPDATE risk_state SET state = @j, updated_at = @t WHERE world = @w", cancellationToken, ("j", json), ("t", now), ("w", world)).ConfigureAwait(false) == 0) + { + await s.ExecuteAsync("INSERT INTO risk_state (id, world, state, created_at, updated_at) VALUES (@id, @w, @j, @t, @t)", cancellationToken, + ("id", Ids.NewId(clock)), ("w", world), ("j", json), ("t", now)).ConfigureAwait(false); + } + }, cancellationToken); + + private Task RecordAsync(string? world, string kind, string severity, string message, object? data, CancellationToken cancellationToken) => + db.WriteAsync(async s => + { + var now = clock.UtcNow; + await s.ExecuteAsync("INSERT INTO risk_events (id, occurred_at, kind, severity, message, data, created_at, world) VALUES (@id, @t, @k, @sev, @m, @d, @t, @w)", cancellationToken, + ("id", Ids.NewId(clock)), ("t", now), ("k", kind), ("sev", severity), ("m", message), ("d", data is null ? null : new DbJson(JsonSerializer.Serialize(data))), ("w", world)) + .ConfigureAwait(false); + if (severity is RiskSeverities.Info) + { + await Diary.WriteAsync(s, clock, DiaryKinds.System, kind, message, data, cancellationToken).ConfigureAwait(false); + } + else + { + await Diary.NotifyAsync(s, clock, kind, message, cancellationToken).ConfigureAwait(false); + } + }, cancellationToken); +} diff --git a/src/Anubis/Trading/Stages.cs b/src/Anubis/Trading/Stages.cs new file mode 100644 index 0000000..85ebb7c --- /dev/null +++ b/src/Anubis/Trading/Stages.cs @@ -0,0 +1,753 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; +using Anubis.Core; +using Anubis.Db; +using Anubis.Risk; + +namespace Anubis.Trading; + +/// The stages of SPEC 12.3. The stage decides where a strategy's orders go (SPEC 7.1). +public static class StrategyStages +{ + public const string Observation = "observation"; + public const string Simulation = "simulation"; + public const string Reduced = "reduced"; + public const string Real = "real"; + + public static readonly IReadOnlyListAll = [Observation, Simulation, Reduced, Real]; + + public static bool IsLive(string stage) => stage is Reduced or Real; + + public static string Label(string stage) => stage switch + { + Observation => "osservazione", + Simulation => "simulazione", + Reduced => "reale ridotto", + Real => "reale", + _ => stage, + }; + + /// A strategy in reduced real works with a quarter of its capital (SPEC 12.3). + public const decimal ReducedShare = 0.25m; +} + +///+/// The backtest outcome a strategy qualified with (SPEC 12.3): it travels with the code in +public sealed record Qualification +{ + public required bool Passed { get; init; } + + ///docs/backtests/ +/// and the requirements and demotions compare against it. It does not move when estimates are updated (11.6). +///Why it passed or not, in plain Italian. + public required string Verdict { get; init; } + + ///The report it comes from: a file of + public required string Report { get; init; } + + public string? PlanHash { get; init; } + + ///docs/backtests/ and the plan's hash.+ /// The parameters of the variant that qualified, as the report writes them ( + public string? Parameters { get; init; } + + ///coin_vol=10;max_stop=20 ): the + /// strategy runs live with these, so the figures it is compared with are those of the rules it follows. + ///Largest fall of the backtest, as a fraction of the capital used: 0.18 is −18%. + public decimal MaxDrawdown { get; init; } + + ///Slippage the backtest assumed, in basis points of the price. + public decimal ExpectedSlippageBp { get; init; } + + ///Estimated round-trip cost, as a fraction of the value traded (fees and slippage, both ways). + public decimal RoundTripCost { get; init; } + + ///+ /// The 5th percentile of the cumulative result after each day from the promotion (SPEC 12.3), from a block + /// bootstrap of the backtest's daily returns: −0.05 is −5%. + /// + public IReadOnlyListExpectedPathP5 { get; init; } = []; + + public static readonly JsonSerializerOptions Json = new() + { + PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + }; +} + +/// A strategy where it stands: stage, accounts, capital, and whether it is only closing real positions. +public sealed record StrategyStage( + string Strategy, + Guid? AccountId, + Guid? LiveAccountId, + string Stage, + bool ExitOnly, + DateTimeOffset? LiveConfirmedAt, + DateTimeOffset? StageSince, + string? StageReason, + decimal Share, + decimal Capital, + Qualification? Qualification) +{ + ///Where the orders of a new decision go: nowhere in observation, the simulation account in simulation, the real one in reduced and real. + public Guid? OrdersAccount => Stage switch + { + StrategyStages.Observation => null, + StrategyStages.Simulation => AccountId, + _ => LiveAccountId, + }; + + ///A strategy with real money keeps running in simulation too: the simulated twin (SPEC 12.3). + public bool HasTwin => StrategyStages.IsLive(Stage); +} + +///One requirement of SPEC 12.3, checked automatically and shown in the interface. +public sealed record Requirement(string Key, string Label, string Value, string Target, bool Met); + +///A condition of automatic demotion in progress (SPEC 12.3). +public sealed record DemotionCondition(string Key, string Message); + +///What the user confirms with the procedure of SPEC 12.4. +public sealed record LiveConfirmation(string Strategy, Guid LiveAccountId, string Phrase, string Password, string? Code, string By); + +public sealed class LiveConfirmationException(string code, string message) : InvalidOperationException(message) +{ + public string Code { get; } = code; +} + +///+/// 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. +/// +public sealed record CarriedResults(IReadOnlyDictionaryCarried, IReadOnlyDictionary