Fase 5 — Strategie, portafoglio e rischio #91
No files matched your search
@@ -7,6 +7,7 @@ artifacts/
|
|||||||
TestResults/
|
TestResults/
|
||||||
docs/
|
docs/
|
||||||
!docs/design/logo/
|
!docs/design/logo/
|
||||||
|
!docs/backtests/*.outcome.json
|
||||||
**/*.md
|
**/*.md
|
||||||
.env
|
.env
|
||||||
.env.*
|
.env.*
|
||||||
@@ -11,6 +11,8 @@ COPY src/Anubis/ src/Anubis/
|
|||||||
COPY src/Anubis.Server/ src/Anubis.Server/
|
COPY src/Anubis.Server/ src/Anubis.Server/
|
||||||
# The logo is embedded from docs/design/logo, its only source (ADR 0005).
|
# The logo is embedded from docs/design/logo, its only source (ADR 0005).
|
||||||
COPY docs/design/logo/ docs/design/logo/
|
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
|
RUN dotnet publish src/Anubis.Server/Anubis.Server.csproj -c Release --no-restore -o /app
|
||||||
|
|
||||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0
|
FROM mcr.microsoft.com/dotnet/aspnet:10.0
|
||||||
|
|||||||
+16
-16
@@ -156,25 +156,25 @@ Le tre strategie di base dentro un motore del rischio che nessuno può aggirare.
|
|||||||
|
|
||||||
**Lavori**
|
**Lavori**
|
||||||
|
|
||||||
- [ ] [#38](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/38) Strategia `crypto_trend`
|
- [x] [#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`
|
- [x] [#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`
|
- [x] [#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
|
- [x] [#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
|
- [x] [#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
|
- [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
|
||||||
- [ ] [#44](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/44) Backtest onesti delle tre strategie in docs/backtests/
|
- [x] [#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
|
- [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
|
||||||
- [ ] [#46](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/46) Chiusura della fase, revisione indipendente e tag `fase-5`
|
- [x] [#46](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/46) Chiusura della fase, revisione indipendente e tag `fase-5`
|
||||||
|
|
||||||
**Criteri di accettazione**
|
**Criteri di accettazione**
|
||||||
|
|
||||||
- [ ] Ogni regola di 9.1 e 9.2 ha il suo test
|
- [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à)
|
||||||
- [ ] Un test dimostra che senza la procedura di 12.4 nessun ordine raggiunge un conto reale
|
- [x] Un test dimostra che senza la procedura di 12.4 nessun ordine raggiunge un conto reale (`NoOrderReachesARealAccountWithoutTheProcedure`)
|
||||||
- [ ] Un test dimostra che una strategia retrocessa continua a gestire uscite e stop delle sue posizioni reali fino a zero
|
- [x] Un test dimostra che una strategia retrocessa continua a gestire uscite e stop delle sue posizioni reali fino a zero (`ADemotedStrategyKeepsManagingItsRealPositionsDownToZero`)
|
||||||
- [ ] 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
|
- [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`
|
||||||
- [ ] Senza chiavi Alpaca i backtest azionari restano in attesa dell'utente e le due strategie azionarie restano in osservazione
|
- [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)
|
||||||
- [ ] I test anti-sguardo-avanti passano
|
- [x] I test anti-sguardo-avanti passano (`CryptoTrendDoesNotLookAhead`, `EquityMomentumDoesNotLookAhead`, `EquityMeanrevDoesNotLookAhead`)
|
||||||
- [ ] Le schermate Strategie, Rischio e Operazioni corrispondono ai mockup
|
- [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
|
## Fase 6 — Motore dal vivo in simulazione
|
||||||
|
|
||||||
|
|||||||
+15
-5
@@ -4,7 +4,7 @@ Aggiornato: 2026-11-11
|
|||||||
|
|
||||||
## Fase corrente
|
## 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
|
## 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.
|
- 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.
|
- 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.
|
- 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
|
## In corso
|
||||||
|
|
||||||
@@ -77,7 +84,7 @@ Nulla.
|
|||||||
|
|
||||||
## Prossimo passo
|
## 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
|
## 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`.
|
- `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).
|
- 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).
|
- 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.
|
- 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.
|
- 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).
|
- 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 |
|
| Cosa | Da quando serve | Senza |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| Via libera per la Fase 5 | Subito | Non si parte |
|
| 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 in attesa |
|
| 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 |
|
| 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 |
|
| 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 |
|
| Token del bot Telegram e chat autorizzata (facoltativi) | Fase 6 | Test con un finto server |
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -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
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -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.
|
||||||
|
|
||||||
@@ -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": []
|
||||||
|
}
|
||||||
@@ -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.
|
||||||
|
|
||||||
@@ -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": []
|
||||||
|
}
|
||||||
@@ -292,8 +292,23 @@ internal sealed partial class AnubisHost(
|
|||||||
: null;
|
: null;
|
||||||
_trading = TradingEnabled && (identity.File ?? Installation.ReadFile(Config.Data)) is { } file
|
_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,
|
? 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;
|
: 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.
|
// 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);
|
_lab = options.Demo ? null : new Laboratory(_db, clock, Config.Data.Research, logger);
|
||||||
_services = new AppServices(_db, settings, secrets, access, backups, scheduler, _market, _trading, _lab);
|
_services = new AppServices(_db, settings, secrets, access, backups, scheduler, _market, _trading, _lab);
|
||||||
|
|||||||
@@ -224,6 +224,7 @@ textarea {
|
|||||||
.panel > h2 { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; }
|
.panel > h2 { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; }
|
||||||
.panel > h3, .panel h3 { margin: 20px 0 8px; }
|
.panel > h3, .panel h3 { margin: 20px 0 8px; }
|
||||||
.note { color: var(--text-3); font-size: 13px; line-height: 18px; }
|
.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; }
|
.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 { 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; }
|
.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; }
|
.currency-lines dd { margin: 0; text-align: right; }
|
||||||
.fx-warning { margin-top: 16px; }
|
.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 pages ---- */
|
||||||
.service { min-height: 100vh; display: flex; justify-content: center; padding: 48px 16px; }
|
.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; }
|
.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; }
|
.panel-tools { width: 100%; justify-content: space-between; }
|
||||||
.facts { grid-template-columns: 1fr; gap: 2px; }
|
.facts { grid-template-columns: 1fr; gap: 2px; }
|
||||||
.facts dd { margin-bottom: 8px; }
|
.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 {
|
.bottombar {
|
||||||
display: grid; grid-template-columns: repeat(5, 1fr); gap: 4px; position: fixed; left: 0; right: 0; bottom: 0;
|
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;
|
padding: 6px 6px calc(6px + env(safe-area-inset-bottom)); background: var(--surface); border-top: 1px solid var(--rule); z-index: 10;
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// "anubis backtest base": the honest backtests of the base strategies (SPEC 12.2, issue #44). It downloads the
|
||||||
|
/// Binance daily archives (each checked against its SHA-256) and the ECB rates into the research history, converts
|
||||||
|
/// them to euro, runs the protocol of <c>crypto_trend</c> on both universes and writes reports and outcome files.
|
||||||
|
/// The stock strategies need the Alpaca history: without it their files say they wait, and they stay in observation.
|
||||||
|
/// </summary>
|
||||||
|
internal static class BacktestCommand
|
||||||
|
{
|
||||||
|
private const string Usage =
|
||||||
|
"Uso: anubis backtest base [--to AAAA-MM-GG] [--out docs/backtests] [--offline]\n" +
|
||||||
|
" --offline usa solo gli archivi già scaricati (i cambi BCE li scarica solo se mancano). Opzioni comuni: [--platform docker|desktop] [--data-dir <cartella>]";
|
||||||
|
|
||||||
|
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null,
|
||||||
|
HttpMessageHandler? handler = null)
|
||||||
|
{
|
||||||
|
output ??= Console.Out;
|
||||||
|
if (args.Length < 1 || args[0] != "base")
|
||||||
|
{
|
||||||
|
await output.WriteLineAsync(Usage).ConfigureAwait(false);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
var rest = args[1..].ToList();
|
||||||
|
environment ??= Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
|
||||||
|
var options = ServerOptions.Parse([.. rest.Where(a => a != "--offline")], environment);
|
||||||
|
var config = options.LoadConfig(environment);
|
||||||
|
var clock = new SystemClock();
|
||||||
|
var now = clock.UtcNow;
|
||||||
|
var to = Option(rest, "--to") is { } t
|
||||||
|
? DateOnly.ParseExact(t, "yyyy-MM-dd", CultureInfo.InvariantCulture)
|
||||||
|
: new DateOnly(now.Year, now.Month, 1).AddDays(-1); // The last month whose archive is published.
|
||||||
|
var outDir = Path.GetFullPath(Option(rest, "--out") ?? Path.Combine("docs", "backtests"));
|
||||||
|
try
|
||||||
|
{
|
||||||
|
config.Data.Ensure();
|
||||||
|
Directory.CreateDirectory(outDir);
|
||||||
|
var store = new ResearchStore(config.Data.Research);
|
||||||
|
IReadOnlyList<FxRate> rates;
|
||||||
|
using (var http = handler is null ? new HttpClient() : new HttpClient(handler, disposeHandler: false))
|
||||||
|
{
|
||||||
|
http.Timeout = TimeSpan.FromMinutes(5);
|
||||||
|
http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}");
|
||||||
|
rates = await RatesAsync(new ApiHttp(http, clock, "ecb"), config.Data.Research, rest.Contains("--offline"), output).ConfigureAwait(false);
|
||||||
|
if (!rest.Contains("--offline"))
|
||||||
|
{
|
||||||
|
var importer = new BinanceImporter(new ApiHttp(http, clock, "binance"), store, clock);
|
||||||
|
foreach (var symbol in CryptoTrendProtocol.Archives)
|
||||||
|
{
|
||||||
|
var result = await importer.ImportAsync(symbol, "1d", 2017, 8, CancellationToken.None).ConfigureAwait(false);
|
||||||
|
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, $"{symbol}: {result.Bars} barre giornaliere")).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var converted = await EuroHistory.ConvertAllAsync(store, rates, CancellationToken.None).ConfigureAwait(false);
|
||||||
|
await output.WriteLineAsync($"Convertite in euro {converted.Count} coppie.").ConfigureAwait(false);
|
||||||
|
|
||||||
|
var outcome = await CryptoTrendProtocol.RunAsync(config.Data.Research, to, now, text => output.WriteLine(text), CancellationToken.None).ConfigureAwait(false);
|
||||||
|
var notes = DataNotes(outcome, rates);
|
||||||
|
await File.WriteAllTextAsync(Path.Combine(outDir, "crypto_trend.md"),
|
||||||
|
ProtocolReport.Markdown(outcome, "crypto_trend", notes, "anubis backtest base --to " + to.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture))).ConfigureAwait(false);
|
||||||
|
await File.WriteAllTextAsync(Path.Combine(outDir, "crypto_trend.outcome.json"), BacktestOutcomes.ToJson(outcome.Qualification)).ConfigureAwait(false);
|
||||||
|
foreach (var run in outcome.Runs)
|
||||||
|
{
|
||||||
|
// The full reports (curve, trades) stay with the data: the repository keeps the summary and the outcome.
|
||||||
|
await File.WriteAllTextAsync(Path.Combine(config.Data.Research, "crypto_trend-" + run.Report.PlanHash[..12] + ".report.json"), run.Report.ToJson())
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var (strategy, name) in new[] { (StrategyNames.EquityMomentum, "Momentum azioni"), (StrategyNames.EquityMeanrev, "Ritorno alla media azioni") })
|
||||||
|
{
|
||||||
|
var waiting = EquityProtocol.Waiting(strategy);
|
||||||
|
await File.WriteAllTextAsync(Path.Combine(outDir, strategy + ".md"), ProtocolReport.Waiting(strategy, name, waiting, EquityProtocol.Explanation)).ConfigureAwait(false);
|
||||||
|
await File.WriteAllTextAsync(Path.Combine(outDir, strategy + ".outcome.json"), BacktestOutcomes.ToJson(waiting)).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
await output.WriteLineAsync((outcome.Qualification.Passed ? "Superato: " : "Non superato: ") + outcome.Qualification.Verdict).ConfigureAwait(false);
|
||||||
|
await output.WriteLineAsync("Rapporti scritti in " + outDir).ConfigureAwait(false);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex is IOException or MarketDataException or HttpRequestException or FormatException or InvalidOperationException
|
||||||
|
or UnauthorizedAccessException or TaskCanceledException or System.IO.InvalidDataException)
|
||||||
|
{
|
||||||
|
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The ECB history of EUR/USD, kept next to the research data so an offline run uses the same rates.</summary>
|
||||||
|
private static async Task<IReadOnlyList<FxRate>> RatesAsync(ApiHttp http, string researchRoot, bool offline, TextWriter output)
|
||||||
|
{
|
||||||
|
var path = Path.Combine(researchRoot, "ecb-eurofxref-hist.zip");
|
||||||
|
if (!offline || !File.Exists(path))
|
||||||
|
{
|
||||||
|
var zip = await http.GetBytesAsync(Ecb.History, null, null, CancellationToken.None).ConfigureAwait(false)
|
||||||
|
?? throw new MarketDataException("BCE: lo storico dei cambi non è disponibile.", retryable: true);
|
||||||
|
await File.WriteAllBytesAsync(path, zip).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
var rates = Ecb.ParseHistoryCsv(Ecb.ExtractHistoryCsv(await File.ReadAllBytesAsync(path).ConfigureAwait(false)), ["USD"]);
|
||||||
|
await output.WriteLineAsync(string.Create(CultureInfo.InvariantCulture, $"Cambi BCE EUR/USD: {rates.Count} giorni, dal {rates[0].Date:yyyy-MM-dd} al {rates[^1].Date:yyyy-MM-dd}."))
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
return rates;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<string> DataNotes(ProtocolOutcome outcome, IReadOnlyList<FxRate> rates)
|
||||||
|
{
|
||||||
|
var broad = outcome.Runs[0].Report.Instruments;
|
||||||
|
var it = CultureInfo.GetCultureInfo("it-IT");
|
||||||
|
var missing = CryptoTrendProtocol.Archives.Select(EuroHistory.SymbolOf).Where(s => broad.All(i => i.Symbol != s)).ToList();
|
||||||
|
var notes = new List<string>
|
||||||
|
{
|
||||||
|
"Archivi giornalieri di data.binance.vision in USDT, ogni file controllato con la sua impronta SHA-256 prima dell'uso.",
|
||||||
|
string.Create(it, $"Prezzi convertiti in euro con il cambio EUR/USD della BCE del giorno ({rates.Count} 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)."),
|
||||||
|
string.Create(it, $"{broad.Count} 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.",
|
||||||
|
};
|
||||||
|
if (missing.Count > 0)
|
||||||
|
{
|
||||||
|
notes.Add("Senza archivi nel periodo, quindi non usate: " + string.Join(", ", missing) + ".");
|
||||||
|
}
|
||||||
|
|
||||||
|
return notes;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? Option(List<string> args, string name)
|
||||||
|
{
|
||||||
|
var index = args.IndexOf(name);
|
||||||
|
return index >= 0 && index < args.Count - 1 ? args[index + 1] : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -80,6 +80,15 @@
|
|||||||
case "lock":
|
case "lock":
|
||||||
<rect x="5" y="10.5" width="14" height="10" rx="2.2" /><path d="M8.5 10.5V7.8a3.5 3.5 0 0 1 7 0v2.7" />
|
<rect x="5" y="10.5" width="14" height="10" rx="2.2" /><path d="M8.5 10.5V7.8a3.5 3.5 0 0 1 7 0v2.7" />
|
||||||
break;
|
break;
|
||||||
|
case "search":
|
||||||
|
<circle cx="11" cy="11" r="6.5" /><path d="m16 16 4 4" />
|
||||||
|
break;
|
||||||
|
case "ban":
|
||||||
|
<circle cx="12" cy="12" r="8.5" /><path d="m6 6 12 12" />
|
||||||
|
break;
|
||||||
|
case "tick":
|
||||||
|
<path d="m5 12.5 4.5 4.5L19 7.5" />
|
||||||
|
break;
|
||||||
case "logout":
|
case "logout":
|
||||||
<path d="M14 4h4.5A1.5 1.5 0 0 1 20 5.5v13a1.5 1.5 0 0 1-1.5 1.5H14M10 16l-4-4 4-4M6 12h10" />
|
<path d="M14 4h4.5A1.5 1.5 0 0 1 20 5.5v13a1.5 1.5 0 0 1-1.5 1.5H14M10 16l-4-4 4-4M6 12h10" />
|
||||||
break;
|
break;
|
||||||
|
|||||||
@@ -21,6 +21,9 @@
|
|||||||
"chiavi" => "Chiavi verificate e salvate: possono fare ordini e non possono prelevare. Il motore è ripartito e le usa.",
|
"chiavi" => "Chiavi verificate e salvate: possono fare ordini e non possono prelevare. Il motore è ripartito e le usa.",
|
||||||
"chiavi-tolte" => "Chiavi tolte: quel conto torna al simulatore interno per le strategie che non hanno ancora storia sul conto di prova.",
|
"chiavi-tolte" => "Chiavi tolte: quel conto torna al simulatore interno per le strategie che non hanno ancora storia sul conto di prova.",
|
||||||
"capitale" => "Capitale affidato aggiornato e diviso tra le strategie.",
|
"capitale" => "Capitale affidato aggiornato e diviso tra le strategie.",
|
||||||
|
"limiti" => "Limiti di rischio salvati.",
|
||||||
|
"rischio" => "Impostazione del rischio salvata.",
|
||||||
|
|
||||||
_ => "Fatto.",
|
_ => "Fatto.",
|
||||||
})</p>
|
})</p>
|
||||||
}
|
}
|
||||||
@@ -30,7 +33,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
<nav class="tabs" aria-label="Sezioni delle impostazioni">
|
<nav class="tabs" aria-label="Sezioni delle impostazioni">
|
||||||
<a href="#aspetto">Aspetto</a><a href="#conti">Conti</a><a href="#dati">Dati</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
|
<a href="#aspetto">Aspetto</a><a href="#conti">Conti</a><a href="#rischio">Rischio</a><a href="#dati">Dati</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
<section class="panel" id="aspetto">
|
<section class="panel" id="aspetto">
|
||||||
@@ -135,7 +138,56 @@
|
|||||||
}
|
}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" id="rischio">
|
||||||
|
<h2>Rischio</h2>
|
||||||
|
<p class="note">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.")</p>
|
||||||
|
@if (!Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/rischio/limiti" class="form-grid limits-form">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
@foreach (var l in _limits)
|
||||||
|
{
|
||||||
|
<label>@l.Label<input name="@l.Key" value="@l.Value" inputmode="decimal" autocomplete="off" readonly="@l.ReadOnly" /></label>
|
||||||
|
}
|
||||||
|
@if (_anyLive)
|
||||||
|
{
|
||||||
|
<label>Per alzare un limite scrivi: <code>@StageBook.RaisePhrase</code><input name="frase" autocomplete="off" /></label>
|
||||||
|
<label>Password<input name="password" type="password" autocomplete="current-password" /></label>
|
||||||
|
<label>Codice a sei cifre (se attivo)<input name="codice" inputmode="numeric" autocomplete="one-time-code" /></label>
|
||||||
|
}
|
||||||
|
<button class="btn" type="submit">Salva i limiti</button>
|
||||||
|
</form>
|
||||||
|
<h3>Protezione day trade</h3>
|
||||||
|
<form method="post" action="/azioni/rischio/@Anubis.Risk.RiskSettings.PdtGuard.Key" class="form-inline">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<label for="pdt">Per un conto Alpaca sotto i 25.000 $: al massimo 3 operazioni aperte e chiuse in giornata ogni 5 sedute.</label>
|
||||||
|
<select id="pdt" name="valore" data-autosubmit>
|
||||||
|
<option value="off" selected="@(_pdt == "off")">Spenta</option>
|
||||||
|
<option value="on" selected="@(_pdt == "on")">Accesa</option>
|
||||||
|
</select>
|
||||||
|
<noscript><button class="btn btn-small" type="submit">Salva</button></noscript>
|
||||||
|
</form>
|
||||||
|
<h3>Scenari «Se succedesse domani»</h3>
|
||||||
|
<form method="post" action="/azioni/rischio/@Anubis.Risk.Scenarios.Setting.Key" class="form">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<label for="scenari">Uno per riga: descrizione; variazione delle crypto %; delle azioni USA %; del dollaro sull'euro %. Per esempio «Le crypto perdono il 20% in un giorno; -20; 0; 0».</label>
|
||||||
|
<textarea id="scenari" name="valore" rows="5" spellcheck="false">@_scenarios</textarea>
|
||||||
|
<button class="btn" type="submit">Salva gli scenari</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<dl class="facts">
|
||||||
|
@foreach (var l in _limits)
|
||||||
|
{
|
||||||
|
<dt>@l.Label</dt><dd>@l.Value</dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
<section class="panel" id="dati">
|
<section class="panel" id="dati">
|
||||||
|
|
||||||
<h2>Dati</h2>
|
<h2>Dati</h2>
|
||||||
@if (Host.Services!.MarketData is not { } market)
|
@if (Host.Services!.MarketData is not { } market)
|
||||||
{
|
{
|
||||||
@@ -302,7 +354,13 @@
|
|||||||
|
|
||||||
private sealed record BrokerSetup(string Broker, string Title, string Short, IReadOnlyList<BrokerKey> Keys, AccountState? State, EntrustedCapital? Entrusted,
|
private sealed record BrokerSetup(string Broker, string Title, string Short, IReadOnlyList<BrokerKey> Keys, AccountState? State, EntrustedCapital? Entrusted,
|
||||||
IReadOnlyList<StrategyCapital> Strategies);
|
IReadOnlyList<StrategyCapital> Strategies);
|
||||||
|
private sealed record LimitField(string Key, string Label, string Value, bool ReadOnly);
|
||||||
|
private readonly List<LimitField> _limits = [];
|
||||||
|
private bool _anyLive;
|
||||||
|
private string _pdt = "off";
|
||||||
|
private string _scenarios = "";
|
||||||
private IReadOnlyList<Anubis.Data.SourceState> _sources = [];
|
private IReadOnlyList<Anubis.Data.SourceState> _sources = [];
|
||||||
|
|
||||||
private SettingValue _meetings = new(SettingsStore.CentralBankMeetings.Key, "", false, null);
|
private SettingValue _meetings = new(SettingsStore.CentralBankMeetings.Key, "", false, null);
|
||||||
private List<SettingChange> _history = [];
|
private List<SettingChange> _history = [];
|
||||||
private IReadOnlyList<BackupInfo> _backups = [];
|
private IReadOnlyList<BackupInfo> _backups = [];
|
||||||
@@ -328,6 +386,16 @@
|
|||||||
_history = await services.Settings.HistoryAsync(null, 50, ct);
|
_history = await services.Settings.HistoryAsync(null, 50, ct);
|
||||||
_meetings = await services.Settings.GetAsync(SettingsStore.CentralBankMeetings.Key, ct);
|
_meetings = await services.Settings.GetAsync(SettingsStore.CentralBankMeetings.Key, ct);
|
||||||
_sources = await new Anubis.Data.SourceStateStore(services.Db, Clock).ListAsync(ct);
|
_sources = await new Anubis.Data.SourceStateStore(services.Db, Clock).ListAsync(ct);
|
||||||
|
foreach (var definition in Anubis.Risk.RiskSettings.Limits)
|
||||||
|
{
|
||||||
|
var value = await services.Settings.GetAsync(definition.Key, ct);
|
||||||
|
_limits.Add(new LimitField(definition.Key, definition.Label, value.Value, value.ReadOnly));
|
||||||
|
}
|
||||||
|
|
||||||
|
_pdt = (await services.Settings.GetAsync(Anubis.Risk.RiskSettings.PdtGuard.Key, ct)).Value;
|
||||||
|
_scenarios = (await services.Settings.GetAsync(Anubis.Risk.Scenarios.Setting.Key, ct)).Value;
|
||||||
|
_anyLive = await (services.Trading?.Stages ?? new StageBook(services.Db, Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false))).AnyLiveAsync(null, ct);
|
||||||
|
|
||||||
_backups = services.Backups.List();
|
_backups = services.Backups.List();
|
||||||
var ledger = new Ledger(services.Db, Clock);
|
var ledger = new Ledger(services.Db, Clock);
|
||||||
var capital = new Capital(services.Db, Clock, ledger, new FxStore(services.Db, Clock));
|
var capital = new Capital(services.Db, Clock, ledger, new FxStore(services.Db, Clock));
|
||||||
@@ -372,6 +440,13 @@
|
|||||||
"importo" => "Scrivi un importo in euro, per esempio 4000 o 1.500,50.",
|
"importo" => "Scrivi un importo in euro, per esempio 4000 o 1.500,50.",
|
||||||
"cambio" => "Manca ancora il cambio euro/dollaro della BCE: lo scarico ogni giorno, riprova più tardi.",
|
"cambio" => "Manca ancora il cambio euro/dollaro della BCE: lo scarico ogni giorno, riprova più tardi.",
|
||||||
"capitale" => "Una strategia ha investito più di quanto le resterebbe: potrò ridurre il capitale quando avrà venduto.",
|
"capitale" => "Una strategia ha investito più di quanto le resterebbe: potrò ridurre il capitale quando avrà venduto.",
|
||||||
|
"limite" => "Un limite non è valido: controlla che ogni valore sia un numero dentro il suo intervallo.",
|
||||||
|
"ordine-limiti" => "Il dimezzamento sul calo dal massimo deve venire prima dell'interruttore, e la perdita di un giorno non può superare quella di una settimana.",
|
||||||
|
"frase-rischio" => $"Una strategia usa soldi veri: per aggiungere rischio scrivi la frase «{StageBook.RaisePhrase}». Non ho cambiato nulla.",
|
||||||
|
"password-rischio" => "Password o codice non corretti. Dopo cinque tentativi sbagliati devi aspettare 15 minuti. Non ho cambiato nulla.",
|
||||||
|
"retrocessione-rischio" => "Una strategia con soldi veri ha una condizione di retrocessione in corso: finché dura non si aggiunge rischio. Non ho cambiato nulla.",
|
||||||
|
"scenari" => "Gli scenari non sono validi: una riga ciascuno, con descrizione e tre percentuali separate da punto e virgola.",
|
||||||
|
|
||||||
_ => PasswordMessages.For(Errore),
|
_ => PasswordMessages.For(Errore),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -254,7 +254,7 @@
|
|||||||
</ul>
|
</ul>
|
||||||
@if (r.Notes.Count > 0)
|
@if (r.Notes.Count > 0)
|
||||||
{
|
{
|
||||||
<h3>Ordini non eseguiti come chiesto</h3>
|
<h3>Decisioni e ordini non eseguiti come chiesto</h3>
|
||||||
<ul>
|
<ul>
|
||||||
@foreach (var (reason, count) in r.Notes.OrderByDescending(n => n.Value))
|
@foreach (var (reason, count) in r.Notes.OrderByDescending(n => n.Value))
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,5 +1,233 @@
|
|||||||
|
@inherits LoadedComponent
|
||||||
@page "/operazioni"
|
@page "/operazioni"
|
||||||
|
@inject AnubisHost Host
|
||||||
|
@inject ShellData Shell
|
||||||
|
@inject IClock Clock
|
||||||
|
@using Anubis.Trading
|
||||||
|
|
||||||
<PageTitle>Operazioni · Anubis</PageTitle>
|
<PageTitle>Operazioni · Anubis</PageTitle>
|
||||||
|
|
||||||
<Pending Title="Ancora nessuna operazione chiusa.">Quando il bot comincerà a lavorare, qui troverai ogni operazione con il suo risultato e il perché di ogni ingresso e uscita.</Pending>
|
@{
|
||||||
|
var v = _view;
|
||||||
|
var c = _currency;
|
||||||
|
var f = _filter;
|
||||||
|
}
|
||||||
|
@if (v.Total == 0)
|
||||||
|
{
|
||||||
|
<Pending Title="Ancora nessuna operazione chiusa.">Qui compare ogni operazione quando si chiude: quanto ha reso, quanto è durata e perché il bot ha comprato e venduto. Le strategie in osservazione non operano: le vedi in <a href="/strategie">Strategie</a>.</Pending>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<section class="panel head-block trades-head" aria-label="Il bilancio delle operazioni">
|
||||||
|
<div class="half">
|
||||||
|
<p class="lead">Per ogni euro perso ne ha guadagnati</p>
|
||||||
|
<p class="big-number">@(v.PerEuroLost is { } per ? Shell.Money(per, c) : "—")</p>
|
||||||
|
<p class="note">Guadagni incassati finora: <strong class="@(v.Net >= 0 ? "gain" : "loss")">@Shell.Money(v.Net, c, withSign: true)</strong>@(f.Period == "avvio" && f.Strategy is null && f.Account is null ? "" : " con i filtri scelti")</p>
|
||||||
|
<dl class="cells">
|
||||||
|
<div><dt>In guadagno</dt><dd><strong>@v.Winners su @v.Matching</strong><span>@Format.Percent(v.Matching == 0 ? 0 : (decimal)v.Winners / v.Matching * 100m)</span></dd></div>
|
||||||
|
<div><dt>Guadagno medio</dt><dd><strong>@(v.Winners == 0 ? "—" : Shell.Money(v.Gains / v.Winners, c, withSign: true))</strong><span>su @v.Winners @(v.Winners == 1 ? "operazione" : "operazioni")</span></dd></div>
|
||||||
|
<div><dt>Perdita media</dt><dd><strong>@(v.Losers == 0 ? "—" : Shell.Money(v.Losses / v.Losers, c, withSign: true))</strong><span>su @v.Losers @(v.Losers == 1 ? "operazione" : "operazioni")</span></dd></div>
|
||||||
|
<div><dt>Commissioni</dt><dd><strong>@Shell.Money(v.Fees, c)</strong><span>già tolte</span></dd></div>
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
<div class="half">
|
||||||
|
<h2>Risultato di ogni operazione <span class="note">dalla prima all'ultima; in alto i guadagni, in basso le perdite</span></h2>
|
||||||
|
@if (v.Bars.Count > 0)
|
||||||
|
{
|
||||||
|
var max = Math.Max(1m, v.Bars.Max(b => Math.Abs(b.Eur)));
|
||||||
|
var width = 600m / v.Bars.Count;
|
||||||
|
var best = v.Bars.MaxBy(b => b.Eur);
|
||||||
|
var worst = v.Bars.MinBy(b => b.Eur);
|
||||||
|
<svg class="result-bars" viewBox="0 0 600 180" preserveAspectRatio="none" role="img" aria-label="Risultato di ogni operazione: la migliore @Shell.Money(best.Eur, c, withSign: true) su @best.Symbol, la peggiore @Shell.Money(worst.Eur, c, withSign: true) su @worst.Symbol">
|
||||||
|
<line x1="0" x2="600" y1="90" y2="90" class="axis" />
|
||||||
|
@for (var i = 0; i < v.Bars.Count; i++)
|
||||||
|
{
|
||||||
|
var b = v.Bars[i];
|
||||||
|
var h = Math.Abs(b.Eur) / max * 70m;
|
||||||
|
<rect x="@Css(i * width + width * 0.15m)" y="@Css(b.Eur >= 0 ? 90 - h : 90)" width="@Css(width * 0.7m)" height="@Css(Math.Max(h, 0.5m))" class="@(b.Eur >= 0 ? "gain" : "loss")" />
|
||||||
|
}
|
||||||
|
</svg>
|
||||||
|
<p class="note bars-scale"><span>@Day(v.Bars[0].At)</span><span>@Day(v.Bars[^1].At)</span></p>
|
||||||
|
<p class="note">La migliore <strong class="gain">@Shell.Money(best.Eur, c, withSign: true)</strong> su @best.Symbol, la peggiore <strong class="loss">@Shell.Money(worst.Eur, c, withSign: true)</strong> su @worst.Symbol.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<p class="note">Nessuna operazione con questi filtri.</p>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel" aria-labelledby="elenco">
|
||||||
|
<h2 id="elenco" class="visually-hidden">Operazioni chiuse</h2>
|
||||||
|
<form class="filters" method="get" action="/operazioni">
|
||||||
|
<label class="search"><Icon Name="search" Size="16" /><span class="visually-hidden">Cerca uno strumento</span><input type="search" name="cerca" value="@f.Search" placeholder="Cerca uno strumento" /></label>
|
||||||
|
<label><span class="visually-hidden">Conto</span>
|
||||||
|
<select name="conto" data-autosubmit>
|
||||||
|
<option value="">Tutti i conti</option>
|
||||||
|
@foreach (var (id, name) in v.Accounts)
|
||||||
|
{
|
||||||
|
<option value="@id" selected="@(f.Account == id)">@name</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label><span class="visually-hidden">Strategia</span>
|
||||||
|
<select name="strategia" data-autosubmit>
|
||||||
|
<option value="">Tutte le strategie</option>
|
||||||
|
@foreach (var s in v.Strategies)
|
||||||
|
{
|
||||||
|
<option value="@s" selected="@(f.Strategy == s)">@StrategyNames.Label(s)</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label><span class="visually-hidden">Esito</span>
|
||||||
|
<select name="esito" data-autosubmit>
|
||||||
|
@foreach (var (key, label) in TradeFilter.Results)
|
||||||
|
{
|
||||||
|
<option value="@key" selected="@((f.Result ?? "") == key)">@label</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label><span class="visually-hidden">Periodo</span>
|
||||||
|
<select name="periodo" data-autosubmit>
|
||||||
|
@foreach (var (key, label) in TradeFilter.Periods)
|
||||||
|
{
|
||||||
|
<option value="@key" selected="@(f.Period == key)">@label</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<noscript><button class="btn" type="submit">Filtra</button></noscript>
|
||||||
|
<a class="btn" href="/api/operazioni.csv@(f.Query(1))" download><Icon Name="download" Size="18" />Esporta CSV</a>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
@if (v.Rows.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="note">Nessuna operazione con questi filtri.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<div class="trades" role="list">
|
||||||
|
<div class="trade-row trade-header" aria-hidden="true">
|
||||||
|
<span>Chiusa</span><span>Strumento</span><span class="wide">Strategia</span><span class="wide">Durata</span><span class="num wide">Entrata e uscita</span><span class="num">Risultato</span><span class="wide">Perché è stata chiusa</span>
|
||||||
|
</div>
|
||||||
|
@foreach (var t in v.Rows)
|
||||||
|
{
|
||||||
|
var gain = t.RealizedEur >= 0;
|
||||||
|
<details class="trade" role="listitem">
|
||||||
|
<summary class="trade-row">
|
||||||
|
<span class="nowrap">@When(t.ClosedAt)</span>
|
||||||
|
<span><strong>@t.Symbol</strong> <span class="muted">@t.Name</span></span>
|
||||||
|
<span class="wide nowrap"><span class="swatch round" style="background: var(--s-@t.Strategy.Replace('_', '-'))"></span>@StrategyNames.Label(t.Strategy)</span>
|
||||||
|
<span class="wide">@Duration(t)</span>
|
||||||
|
<span class="num wide nowrap">@Format.Money(t.EntryPrice, t.Currency, decimals: t.EntryPrice >= 1m ? 2 : 4) → @Format.Money(t.ExitPrice, t.Currency, decimals: t.ExitPrice >= 1m ? 2 : 4)</span>
|
||||||
|
<span class="num nowrap @(gain ? "gain" : "loss")"><strong>@Shell.Money(t.RealizedEur, c, withSign: true)</strong> <span class="cell-extra">(@Format.Percent(t.Percent, 2, withSign: true))</span></span>
|
||||||
|
<span class="wide">@t.ExitReason</span>
|
||||||
|
</summary>
|
||||||
|
<div class="why">
|
||||||
|
<div class="why-card">
|
||||||
|
<h3>Perché l'ho comprata</h3>
|
||||||
|
@if (t.Bought.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="note">Per questa operazione non c'è la traccia della decisione d'acquisto: è precedente al registro delle decisioni o è stata aperta senza strategia.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<ul class="checks">
|
||||||
|
@foreach (var line in t.Bought)
|
||||||
|
{
|
||||||
|
<li class="@(line.Good ? "ok" : "warn")"><Icon Name="@(line.Good ? "check" : "alert")" Size="16" />@line.Text</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
<div class="why-card">
|
||||||
|
<h3>Perché l'ho venduta</h3>
|
||||||
|
@if (t.Sold.Count == 0)
|
||||||
|
{
|
||||||
|
<p>@t.ExitReason.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<ul class="checks">
|
||||||
|
@foreach (var line in t.Sold)
|
||||||
|
{
|
||||||
|
<li class="@(line.Good ? "ok" : "warn")"><Icon Name="@(line.Good ? "check" : "alert")" Size="16" />@line.Text</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
<dl class="account-lines">
|
||||||
|
<dt>Comprata @Long(t.OpenedAt)</dt><dd><strong>@Format.Quantity(t.Quantity) a @Format.Money(t.EntryPrice, t.Currency, decimals: t.EntryPrice >= 1m ? 2 : 4)</strong></dd>
|
||||||
|
<dt>Venduta @Long(t.ClosedAt)</dt><dd><strong>a @Format.Money(t.ExitPrice, t.Currency, decimals: t.ExitPrice >= 1m ? 2 : 4)</strong></dd>
|
||||||
|
<dt>Differenza dal prezzo atteso</dt><dd><strong>@Slip(t.EntrySlipBp) e @Slip(t.ExitSlipBp)</strong></dd>
|
||||||
|
<dt>Commissioni</dt><dd><strong>@Format.Money(t.Fees, t.Currency)</strong></dd>
|
||||||
|
<dt>Conto</dt><dd>@t.Account</dd>
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
var pages = (v.Matching + TradeFilter.PageSize - 1) / TradeFilter.PageSize;
|
||||||
|
<div class="pager">
|
||||||
|
<span class="note">Mostrate @v.Rows.Count di @v.Matching</span>
|
||||||
|
@if (f.Page > 1)
|
||||||
|
{
|
||||||
|
<a class="btn" href="/operazioni@(f.Query(f.Page - 1))">Più recenti</a>
|
||||||
|
}
|
||||||
|
@if (f.Page < pages)
|
||||||
|
{
|
||||||
|
<a class="btn" href="/operazioni@(f.Query(f.Page + 1))">Più vecchie</a>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private TradesView _view = null!;
|
||||||
|
private TradeFilter _filter = null!;
|
||||||
|
private string _currency = "EUR";
|
||||||
|
|
||||||
|
[CascadingParameter]
|
||||||
|
public HttpContext? HttpContext { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "cerca")] public string? Cerca { get; set; }
|
||||||
|
[SupplyParameterFromQuery(Name = "conto")] public string? Conto { get; set; }
|
||||||
|
[SupplyParameterFromQuery(Name = "strategia")] public string? Strategia { get; set; }
|
||||||
|
[SupplyParameterFromQuery(Name = "esito")] public string? Esito { get; set; }
|
||||||
|
[SupplyParameterFromQuery(Name = "periodo")] public string? Periodo { get; set; }
|
||||||
|
[SupplyParameterFromQuery(Name = "pagina")] public string? Pagina { get; set; }
|
||||||
|
|
||||||
|
protected override async Task LoadAsync()
|
||||||
|
{
|
||||||
|
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
|
||||||
|
var services = Host.Services!;
|
||||||
|
_currency = Shell.Effective((await services.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value);
|
||||||
|
_filter = TradeFilter.Parse(Cerca, Conto, Strategia, Esito, Periodo, Pagina);
|
||||||
|
_view = await TradesView.LoadAsync(services, Clock, _filter, null, ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Css(decimal value) => value.ToString("0.##", CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
private string Local(DateTimeOffset at, string format) => TimeZoneInfo.ConvertTime(at, Shell.Zone).ToString(format, CultureInfo.GetCultureInfo("it-IT"));
|
||||||
|
|
||||||
|
private string When(DateTimeOffset at) => Capital(Local(at, "ddd d MMM, HH:mm"));
|
||||||
|
|
||||||
|
private string Day(DateTimeOffset at) => Local(at, "d MMM");
|
||||||
|
|
||||||
|
private string Long(DateTimeOffset at) => Local(at, "dddd d MMMM, HH:mm");
|
||||||
|
|
||||||
|
private static string Capital(string text) => text.Length == 0 ? text : char.ToUpper(text[0], CultureInfo.GetCultureInfo("it-IT")) + text[1..];
|
||||||
|
|
||||||
|
private static string Duration(TradeRow t)
|
||||||
|
{
|
||||||
|
var days = (int)Math.Round((t.ClosedAt - t.OpenedAt).TotalDays);
|
||||||
|
return days switch
|
||||||
|
{
|
||||||
|
< 1 => "in giornata",
|
||||||
|
1 => "1 giorno",
|
||||||
|
_ => $"{days} giorni",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Slip(decimal? bp) => bp is { } b ? Format.Percent(b / 100m, 2) : "—";
|
||||||
|
}
|
||||||
@@ -1,30 +1,307 @@
|
|||||||
@inherits LoadedComponent
|
@inherits LoadedComponent
|
||||||
@page "/rischio"
|
@page "/rischio"
|
||||||
@inject AnubisHost Host
|
@inject AnubisHost Host
|
||||||
|
@inject ShellData Shell
|
||||||
|
@inject IClock Clock
|
||||||
|
@using Anubis.Trading
|
||||||
|
@using Anubis.Risk
|
||||||
|
|
||||||
<PageTitle>Rischio · Anubis</PageTitle>
|
<PageTitle>Rischio · Anubis</PageTitle>
|
||||||
|
|
||||||
<section class="panel">
|
@{
|
||||||
<h2><Icon Name="shield" Size="18" />Interruttore</h2>
|
var v = _view;
|
||||||
@if (_bot == "stopped")
|
var c = _currency;
|
||||||
{
|
}
|
||||||
<p class="notice notice-attention" role="status"><Icon Name="alert" Size="16" />"Ferma tutto" è acceso: il bot non apre e non gestisce operazioni finché non lo riattivi.</p>
|
@if (_message is { } message)
|
||||||
<form method="post" action="/azioni/bot/riattiva" class="form-inline">
|
{
|
||||||
<AntiforgeryToken />
|
<p class="notice notice-loss" role="status"><Icon Name="alert" Size="16" />@message</p>
|
||||||
<input type="hidden" name="ritorno" value="/rischio" />
|
}
|
||||||
<button class="btn" type="submit" data-confirm="Riattivare il bot?">Riattiva il bot</button>
|
<div class="risk-top">
|
||||||
</form>
|
<section class="panel" aria-labelledby="interruttore">
|
||||||
}
|
<div class="panel-head">
|
||||||
else
|
<h2 id="interruttore">Interruttore d'emergenza</h2>
|
||||||
{
|
<span class="link-state @(v.BotState == "active" ? null : "down")"><span class="dot"></span>@BotText(v.BotState)</span>
|
||||||
<p>"Ferma tutto", in alto, blocca il bot. Dopo averlo usato il bot si riattiva solo da qui, mai da solo e mai da Telegram.</p>
|
</div>
|
||||||
}
|
@if (v.WaitsForRestart)
|
||||||
|
{
|
||||||
|
<p class="notice notice-attention" role="status"><Icon Name="alert" Size="16" /><span>
|
||||||
|
@if (v.Tripped.Count > 0)
|
||||||
|
{
|
||||||
|
<text>L'interruttore è scattato @string.Join(" e ", v.Tripped.Select(t => Where(t.World))): il calo dal massimo ha superato il @Format.Percent(v.Limits.DrawdownStop * 100m, 0). </text>
|
||||||
|
}
|
||||||
|
@if (v.BotState == "stopped")
|
||||||
|
{
|
||||||
|
<text>Il bot non apre posizioni e non vende per le strategie; gli stop di protezione restano attivi.</text>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<text>Lì non apro posizioni e non vendo per le strategie; gli stop di protezione restano attivi. Il resto continua a lavorare.</text>
|
||||||
|
}
|
||||||
|
@if (v.CloseAllPending)
|
||||||
|
{
|
||||||
|
<text> Sta vendendo tutte le posizioni: ciò che è su un mercato chiuso parte all'apertura.</text>
|
||||||
|
}
|
||||||
|
</span></p>
|
||||||
|
@if (v.StopFile)
|
||||||
|
{
|
||||||
|
<p class="note">C'è il file <code>STOP</code> nella cartella dei dati: toglilo, poi conferma qui la ripartenza.</p>
|
||||||
|
}
|
||||||
|
@if (!Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/bot/riattiva" class="form-inline">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<input type="hidden" name="ritorno" value="/rischio" />
|
||||||
|
<button class="btn" type="submit" disabled="@v.StopFile" data-confirm="@RestartText(v)">Riparti</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if (v.BotState != "stopped")
|
||||||
|
{
|
||||||
|
<p>Con <strong>Ferma tutto</strong> annullo gli ordini in attesa e non apro nuove posizioni. Gli stop di protezione restano attivi, così quello che è aperto non rimane scoperto. Per ripartire serve la tua conferma, da qui.</p>
|
||||||
|
@if (!Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<div class="choices">
|
||||||
|
<form method="post" action="/azioni/bot/ferma"><AntiforgeryToken /><input type="hidden" name="ritorno" value="/rischio" /><button class="btn btn-danger-solid" type="submit" data-confirm="Ferma tutto: annullo gli ordini in attesa e non apro posizioni finché non riparti da qui. Gli stop restano. Confermi?"><Icon Name="stop" Size="18" />Ferma tutto</button></form>
|
||||||
|
<form method="post" action="/azioni/bot/chiudi"><AntiforgeryToken /><input type="hidden" name="ritorno" value="/rischio" /><button class="btn btn-danger" type="submit" data-confirm="Ferma e chiudi: 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. Non si annulla. Confermi?">Ferma e chiudi tutte le posizioni</button></form>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
<p class="note">Anche un file chiamato <code>STOP</code> nella cartella dei dati ferma tutto entro un minuto.</p>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
<section class="panel" aria-labelledby="blocchi">
|
||||||
|
<h2 id="blocchi">Blocchi automatici</h2>
|
||||||
|
@if (!v.AnyBlock)
|
||||||
|
{
|
||||||
|
<p class="gain status-line"><Icon Name="check" Size="16" />Nessun blocco attivo</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<ul class="blocks">
|
||||||
|
@foreach (var t in v.Tripped)
|
||||||
|
{
|
||||||
|
<li class="loss"><Icon Name="alert" Size="16" />Interruttore scattato @Where(t.World) @(t.State.TrippedAt is { } at ? "il " + Moment(at) : ""): aspetta la tua conferma.</li>
|
||||||
|
}
|
||||||
|
@if (v.Risk.State.DailyBlockUntil is { } until && until > Clock.UtcNow)
|
||||||
|
{
|
||||||
|
<li><Icon Name="clock" Size="16" />Perdita del giorno oltre il limite: niente nuovi ingressi fino a @Moment(until).</li>
|
||||||
|
}
|
||||||
|
@if (v.Risk.State.WeeklyHalvingUntil is { } half && half > Clock.UtcNow)
|
||||||
|
{
|
||||||
|
<li><Icon Name="clock" Size="16" />Perdita della settimana oltre il limite: rischio dimezzato fino a @Moment(half).</li>
|
||||||
|
}
|
||||||
|
@if (v.Risk.Measures.Drawdown <= -v.Limits.DrawdownHalf && !v.Risk.State.Tripped)
|
||||||
|
{
|
||||||
|
<li><Icon Name="alert" Size="16" />Calo dal massimo oltre il @Format.Percent(v.Limits.DrawdownHalf * 100m, 0): rischio dimezzato.</li>
|
||||||
|
}
|
||||||
|
@if (v.BotState == "paused")
|
||||||
|
{
|
||||||
|
<li><Icon Name="pause" Size="16" />Bot in pausa: niente nuovi ingressi, stop e uscite proseguono.</li>
|
||||||
|
}
|
||||||
|
@if (v.BotState == "stopped" && v.Tripped.Count == 0)
|
||||||
|
{
|
||||||
|
<li class="loss"><Icon Name="stop" Size="16" />Ferma tutto acceso.</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
}
|
||||||
|
<dl class="block-list">
|
||||||
|
<dt>Prossimo blocco in programma</dt>
|
||||||
|
@if (v.NextCalendarBlock is { } next)
|
||||||
|
{
|
||||||
|
<dd><strong>@Capital(Local(next.From, "dddd d MMMM")), dalle @Local(next.From, "HH:mm") alle @Local(next.To, "HH:mm")</strong><span>@next.Title: in quell'ora non apro posizioni.</span></dd>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<dd><span>Nessun dato economico importante nei prossimi 14 giorni.</span></dd>
|
||||||
|
}
|
||||||
|
<dt>Ultimo blocco scattato</dt>
|
||||||
|
@if (v.LastCalendarBlock is { } last)
|
||||||
|
{
|
||||||
|
<dd><strong>@Capital(Local(last.From, "dddd d MMMM")), dalle @Local(last.From, "HH:mm") alle @Local(last.To, "HH:mm")</strong><span>@last.Title.</span></dd>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<dd><span>Nessuno negli ultimi 14 giorni.</span></dd>
|
||||||
|
}
|
||||||
|
<dt>Protezione day trade (azioni)</dt>
|
||||||
|
<dd><span>@(v.PdtGuard ? "Accesa: al massimo 3 operazioni in giornata ogni 5 sedute." : "Spenta. Si accende in Impostazioni se il conto Alpaca vale meno di 25.000 $.")</span></dd>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section class="panel" aria-labelledby="limiti">
|
||||||
|
<div class="panel-head">
|
||||||
|
<h2 id="limiti">I limiti <span class="note">Valgono per tutte le strategie insieme@(v.World == Worlds.Real ? ", sui conti veri" : ", nel mondo simulato"). Si cambiano dalle <a href="/impostazioni#rischio">impostazioni</a>, mai da soli.</span></h2>
|
||||||
|
</div>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table limits">
|
||||||
|
<thead>
|
||||||
|
<tr><th scope="col">Limite</th><th scope="col" class="num">Adesso</th><th scope="col" class="wide">Quanto ne sto usando</th><th scope="col" class="num">Soglia</th><th scope="col" class="wide">Se lo supero</th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var row in v.Rows)
|
||||||
|
{
|
||||||
|
<tr>
|
||||||
|
<th scope="row">@row.Label</th>
|
||||||
|
<td class="num nowrap">@row.Now@if (row.Detail is { } d) {<text> </text><span class="muted">(@d)</span>}</td>
|
||||||
|
<td class="wide">
|
||||||
|
@if (row.Usage is { } u)
|
||||||
|
{
|
||||||
|
<span class="usage @(u >= 0.8m ? "high" : null)" role="img" aria-label="@Format.Percent(u * 100m, 0) del limite"><span style="width: @Css(u * 100m)%"></span></span>
|
||||||
|
}
|
||||||
|
</td>
|
||||||
|
<td class="num nowrap">@row.Threshold</td>
|
||||||
|
<td class="wide">@row.Beyond</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
<Pending Title="Limiti e scenari non sono ancora attivi.">Limiti di perdita, calo dal massimo, esposizione e scenari arrivano con le strategie e il controllo del rischio.</Pending>
|
|
||||||
|
<div class="columns">
|
||||||
|
<section class="panel" aria-labelledby="calo">
|
||||||
|
<h2 id="calo">Quanto è sceso dal massimo</h2>
|
||||||
|
<p class="note">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.</p>
|
||||||
|
@if (v.Drawdown.Count < 2)
|
||||||
|
{
|
||||||
|
<p class="note">Ancora troppo poche fotografie per disegnare la curva.</p>
|
||||||
|
}
|
||||||
|
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)));
|
||||||
|
<svg class="drawdown" viewBox="0 0 600 190" role="img" aria-label="Calo dal massimo: il peggiore @Format.Percent(worst.Drawdown * 100m, 2) il @Local(worst.At, "d MMMM")">
|
||||||
|
<line x1="30" x2="590" y1="10" y2="10" class="axis" />
|
||||||
|
<text x="0" y="14" class="tick">0%</text>
|
||||||
|
<text x="0" y="164" class="tick">@Format.Percent(floor * 100m, 1)</text>
|
||||||
|
<polygon points="30,10 @points @X(v.Drawdown[^1].At),10" class="area" />
|
||||||
|
<polyline points="@points" class="line" />
|
||||||
|
<circle cx="@X(worst.At)" cy="@Y(worst.Drawdown)" r="4" class="dot" />
|
||||||
|
<text x="@X(worst.At)" y="@(Css(Math.Min(180m, 26m + worst.Drawdown / floor * 150m)))" text-anchor="middle" class="label">@Format.Percent(worst.Drawdown * 100m, 2) il @Local(worst.At, "d MMM")</text>
|
||||||
|
</svg>
|
||||||
|
<p class="note">
|
||||||
|
@if (-worst.Drawdown < v.Limits.DrawdownHalf / 5m)
|
||||||
|
{
|
||||||
|
<text>Le soglie del @Format.Percent(v.Limits.DrawdownHalf * 100m, 0) e del @Format.Percent(v.Limits.DrawdownStop * 100m, 0) sono fuori scala: il calo peggiore è rimasto sotto un quinto del limite.</text>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<text>A @Format.Percent(-v.Limits.DrawdownHalf * 100m, 0) il rischio si dimezza, a @Format.Percent(-v.Limits.DrawdownStop * 100m, 0) il bot si ferma e aspetta te.</text>
|
||||||
|
}
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
<section class="panel" aria-labelledby="scenari">
|
||||||
|
<h2 id="scenari">Se succedesse domani</h2>
|
||||||
|
<p class="note">Quanto perderei con le posizioni di adesso. Gli scenari si cambiano in <a href="/impostazioni#rischio">Impostazioni</a>.</p>
|
||||||
|
@if (!v.HasPositions)
|
||||||
|
{
|
||||||
|
<p class="note">Nessuna posizione aperta: oggi nessuno scenario costerebbe nulla.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="table">
|
||||||
|
<thead><tr><th scope="col">Scenario</th><th scope="col" class="num">Senza stop</th><th scope="col" class="num">Con gli stop</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var s in v.Scenarios)
|
||||||
|
{
|
||||||
|
<tr>
|
||||||
|
<th scope="row">@s.Scenario.Label</th>
|
||||||
|
<td class="num nowrap"><strong>@Shell.Money(s.WithoutStops, c, decimals: 0)</strong> <span class="muted">(@Format.Percent(s.WithoutStopsShare * 100m, 1, withSign: true))</span></td>
|
||||||
|
<td class="num nowrap muted">@(s.SameWithStops ? "uguale" : "circa " + Shell.Money(s.WithStops ?? 0m, c, decimals: 0))</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<p class="notice notice-attention"><Icon Name="alert" Size="16" />Gli stop non sono una garanzia: in un crollo improvviso il prezzo può saltarli. E nessuno stop protegge dal cambio.</p>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="columns">
|
||||||
|
<section aria-labelledby="mai" class="plain">
|
||||||
|
<h2 id="mai">Cosa il bot non può fare, mai</h2>
|
||||||
|
<ul class="never">
|
||||||
|
<li><Icon Name="ban" Size="16" />Usare soldi presi in prestito o vendere allo scoperto</li>
|
||||||
|
<li><Icon Name="ban" Size="16" />Prelevare o spostare denaro: le chiavi dei conti non lo permettono</li>
|
||||||
|
<li><Icon Name="ban" Size="16" />Toccare posizioni che non ha aperto lui</li>
|
||||||
|
<li><Icon Name="ban" Size="16" />Passare ai soldi veri senza la tua conferma</li>
|
||||||
|
<li><Icon Name="ban" Size="16" />Rischiare di più per recuperare una perdita</li>
|
||||||
|
<li><Icon Name="ban" Size="16" />Comprare di più perché lo suggerisce una notizia o il modello</li>
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
<section aria-labelledby="eventi" class="plain">
|
||||||
|
<div class="panel-head">
|
||||||
|
<h2 id="eventi">Eventi di rischio</h2>
|
||||||
|
@if (v.Events.Count == 0)
|
||||||
|
{
|
||||||
|
<span class="note">Nessun limite superato dall'avvio</span>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
@if (v.Events.Count > 0)
|
||||||
|
{
|
||||||
|
<dl class="events">
|
||||||
|
@foreach (var e in v.Events)
|
||||||
|
{
|
||||||
|
<dt>@Local(e.At, "d MMMM")</dt>
|
||||||
|
<dd class="@(e.Severity is RiskSeverities.Critical or RiskSeverities.High ? "loss" : null)">@e.Message</dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
<a href="/diario">Vedi tutto nel diario</a>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
@code {
|
@code {
|
||||||
private string _bot = "active";
|
private RiskView _view = null!;
|
||||||
|
private string _currency = "EUR";
|
||||||
|
private string? _message;
|
||||||
|
|
||||||
protected override async Task LoadAsync() =>
|
[CascadingParameter]
|
||||||
_bot = (await Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key)).Value;
|
public HttpContext? HttpContext { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "errore")]
|
||||||
|
public string? Errore { get; set; }
|
||||||
|
|
||||||
|
protected override async Task LoadAsync()
|
||||||
|
{
|
||||||
|
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
|
||||||
|
var services = Host.Services!;
|
||||||
|
_currency = Shell.Effective((await services.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value);
|
||||||
|
_view = await RiskView.LoadAsync(services, Clock, Shell.Zone, ct);
|
||||||
|
_message = Errore switch
|
||||||
|
{
|
||||||
|
"file-stop" => "Il file STOP è ancora nella cartella dei dati: toglilo prima di ripartire.",
|
||||||
|
"bot" => "Comando non ammesso nello stato attuale del bot.",
|
||||||
|
_ => null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string BotText(string state) => state switch
|
||||||
|
{
|
||||||
|
"active" => "Il bot sta operando",
|
||||||
|
"paused" => "In pausa",
|
||||||
|
_ => "Fermo",
|
||||||
|
};
|
||||||
|
|
||||||
|
private static string Where(string world) => world == Worlds.Real ? "sui conti veri" : "nel mondo simulato";
|
||||||
|
|
||||||
|
private static string RestartText(RiskView v) => v.Tripped.Count > 0
|
||||||
|
? "Riparti: il massimo di riferimento riparte dal patrimonio di adesso e il bot torna a operare. Confermi?"
|
||||||
|
: "Riparti: il bot torna a operare. Confermi?";
|
||||||
|
|
||||||
|
private static string Css(decimal value) => value.ToString("0.##", CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
private string Local(DateTimeOffset at, string format) => TimeZoneInfo.ConvertTime(at, Shell.Zone).ToString(format, CultureInfo.GetCultureInfo("it-IT"));
|
||||||
|
|
||||||
|
private string Moment(DateTimeOffset at) => Local(at, "d MMMM 'alle' HH:mm");
|
||||||
|
|
||||||
|
private static string Capital(string text) => text.Length == 0 ? text : char.ToUpper(text[0], CultureInfo.GetCultureInfo("it-IT")) + text[1..];
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,246 @@
|
|||||||
|
@inherits LoadedComponent
|
||||||
@page "/strategie"
|
@page "/strategie"
|
||||||
|
@inject AnubisHost Host
|
||||||
|
@inject ShellData Shell
|
||||||
|
@inject IClock Clock
|
||||||
|
@using Anubis.Trading
|
||||||
|
|
||||||
<PageTitle>Strategie · Anubis</PageTitle>
|
<PageTitle>Strategie · Anubis</PageTitle>
|
||||||
|
|
||||||
<Pending Title="Le strategie non sono ancora attive.">Arrivano dopo il laboratorio: ognuna con la sua descrizione, i requisiti per passare allo stadio successivo e i risultati.</Pending>
|
@{
|
||||||
|
var v = _view;
|
||||||
|
var c = _currency;
|
||||||
|
var working = v.Cards.Where(x => x.Stage.Stage != StrategyStages.Observation).ToList();
|
||||||
|
var watching = v.Cards.Where(x => x.Stage.Stage == StrategyStages.Observation).ToList();
|
||||||
|
}
|
||||||
|
@if (_message is { } message)
|
||||||
|
{
|
||||||
|
<p class="notice @(_ok ? "notice-gain" : "notice-loss")" role="status"><Icon Name="@(_ok ? "check" : "alert")" Size="16" />@message</p>
|
||||||
|
}
|
||||||
|
<section class="panel" aria-labelledby="percorso">
|
||||||
|
<h2 id="percorso">Il percorso verso i soldi veri <span class="note">Una strategia avanza solo se supera tutti i requisiti e se lo confermi tu. Se peggiora, torna indietro da sola.</span></h2>
|
||||||
|
<ol class="stages">
|
||||||
|
@foreach (var (stage, i) in new[] { StrategyStages.Observation, StrategyStages.Simulation, StrategyStages.Reduced, StrategyStages.Real }.Select((s, i) => (s, i)))
|
||||||
|
{
|
||||||
|
var here = v.Cards.Where(x => x.Stage.Stage == stage).ToList();
|
||||||
|
<li class="@(here.Count > 0 ? "here" : null)">
|
||||||
|
<span class="step">@(i + 1)</span>
|
||||||
|
<strong>@Capital(StrategyStages.Label(stage))</strong>
|
||||||
|
<p>@StageText(stage)</p>
|
||||||
|
<p class="stage-count">
|
||||||
|
@if (here.Count == 0)
|
||||||
|
{
|
||||||
|
<span class="muted">Nessuna strategia</span>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
@foreach (var x in here)
|
||||||
|
{
|
||||||
|
<span class="swatch round" style="background: @x.Color"></span>
|
||||||
|
}
|
||||||
|
<strong>@(here.Count == 1 ? "1 strategia" : $"{here.Count} strategie")</strong>
|
||||||
|
}
|
||||||
|
</p>
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ol>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@foreach (var s in working)
|
||||||
|
{
|
||||||
|
var up = s.ResultEur >= 0;
|
||||||
|
<section class="panel strategy" aria-label="@s.Name">
|
||||||
|
<div class="strategy-about">
|
||||||
|
<h2><span class="swatch round" style="background: @s.Color"></span>@s.Name <span class="tag">@(s.Stage.ExitOnly ? "Sola uscita" : "In " + StrategyStages.Label(s.Stage.Stage).ToLower(CultureInfo.GetCultureInfo("it-IT")))</span></h2>
|
||||||
|
<p>@s.Description</p>
|
||||||
|
<ul>
|
||||||
|
@foreach (var rule in s.Rules)
|
||||||
|
{
|
||||||
|
<li>@rule</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
<p class="note">Conto @s.Account. Capitale assegnato: @Shell.Money(s.CapitalEur, c, decimals: 0).</p>
|
||||||
|
</div>
|
||||||
|
<div class="strategy-result">
|
||||||
|
<p class="strategy-number">@Shell.Money(s.ResultEur, c, withSign: true) <span class="cell-change @(up ? "gain" : "loss")"><Arrow Up="up" />@Format.Percent(s.ResultPercent, 2, withSign: true)</span></p>
|
||||||
|
@if (s.Curve.Count > 1)
|
||||||
|
{
|
||||||
|
var min = s.Curve.Min(p => p.Index);
|
||||||
|
var max = s.Curve.Max(p => p.Index);
|
||||||
|
var range = Math.Max(0.0001m, max - min);
|
||||||
|
var points = string.Join(' ', s.Curve.Select((p, i) => Css(i * 300m / (s.Curve.Count - 1)) + "," + Css(70m - (p.Index - min) / range * 60m)));
|
||||||
|
<svg class="spark" viewBox="0 0 300 80" role="img" aria-label="Andamento della strategia"><polyline points="@points" style="stroke: @s.Color" /></svg>
|
||||||
|
}
|
||||||
|
<dl class="account-lines">
|
||||||
|
<dt>Calo peggiore</dt><dd><strong>@Format.Percent(s.WorstFall * 100m, 1)</strong></dd>
|
||||||
|
<dt>Operazioni chiuse</dt><dd><strong>@s.Closed@(s.Closed > 0 ? $", di cui {s.Winners} in guadagno" : "")</strong></dd>
|
||||||
|
<dt>Posizioni aperte</dt><dd><strong>@(s.Open.Count == 0 ? "nessuna" : string.Join(", ", s.Open.Distinct()))</strong></dd>
|
||||||
|
@if (s.TwinGap is { } gap)
|
||||||
|
{
|
||||||
|
<dt>Rispetto al gemello simulato</dt><dd><strong>@Format.Percent(gap, 2, withSign: true)</strong> <span class="muted">del capitale usato</span></dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
<div class="strategy-steps">
|
||||||
|
<h3>Requisiti per @(s.Stage.Stage == StrategyStages.Reduced ? "il reale pieno" : StrategyStages.IsLive(s.Stage.Stage) ? "restare con soldi veri" : "usare soldi veri")</h3>
|
||||||
|
<ul class="checks">
|
||||||
|
@foreach (var r in s.Requirements)
|
||||||
|
{
|
||||||
|
<li class="@(r.Met ? "ok" : StrategiesView.IsPending(r) ? "wait" : "warn")">
|
||||||
|
<Icon Name="@(r.Met ? "tick" : StrategiesView.IsPending(r) ? "clock" : "alert")" Size="16" />
|
||||||
|
<span><strong>@r.Label</strong>: @r.Value <span class="muted">(@r.Target)</span></span>
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
@if (s.Stage.ExitOnly)
|
||||||
|
{
|
||||||
|
<p class="notice notice-attention"><Icon Name="alert" Size="16" />Tornata indietro con posizioni vere ancora aperte: le gestisce fino a zero, con i loro stop, senza nuovi acquisti.</p>
|
||||||
|
}
|
||||||
|
@if (StrategyStages.IsLive(s.Stage.Stage) && !Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/strategie/@s.Stage.Strategy/osservazione" class="form-inline">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<button class="btn btn-danger" type="submit" data-confirm="Togli i soldi veri a questa strategia: torna in simulazione e le posizioni vere restano in sola uscita fino a zero. Confermi?">Togli i soldi veri</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
@if (s.Stage.Stage is StrategyStages.Simulation or StrategyStages.Reduced)
|
||||||
|
{
|
||||||
|
var target = s.Stage.Stage == StrategyStages.Reduced ? "Passa al reale" : "Passa al reale ridotto";
|
||||||
|
var broker = StrategyNames.BrokerOf(s.Stage.Strategy);
|
||||||
|
var accounts = v.LiveAccounts.Where(a => a.Broker == broker).ToList();
|
||||||
|
if (!s.AllMet)
|
||||||
|
{
|
||||||
|
<p class="form-inline"><button class="btn" type="button" disabled>@target</button> <span class="note">@(s.DaysToGo is { } d ? $"Disponibile tra {d} {(d == 1 ? "giorno" : "giorni")}, se gli altri requisiti reggono" : "Non ancora: mancano dei requisiti")</span></p>
|
||||||
|
@if (s.Requirements.Any(r => !r.Met && !StrategiesView.IsPending(r)))
|
||||||
|
{
|
||||||
|
<p class="notice notice-attention"><Icon Name="alert" Size="16" />Per ora non merita soldi veri. Resta in simulazione finché non migliora.</p>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (!v.LiveAllowed || accounts.Count == 0 || Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<p class="form-inline"><button class="btn" type="button" disabled>@target</button> <span class="note">@(v.LiveAllowed ? "Serve un conto reale di " + (broker == "okx" ? "OKX" : "Alpaca") + " nelle Impostazioni." : "La configurazione d'avvio non consente i soldi veri.")</span></p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<details class="confirm-live">
|
||||||
|
<summary class="btn">@target</summary>
|
||||||
|
<form method="post" action="/azioni/strategie/@s.Stage.Strategy/reale" class="form-grid">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<p>Stai per affidare soldi veri a <strong>@s.Name</strong>@(s.Stage.Stage == StrategyStages.Simulation ? ", con un quarto del capitale" : ""). Ecco cosa cambia:</p>
|
||||||
|
<ul class="confirm-summary">
|
||||||
|
@foreach (var line in s.Summary)
|
||||||
|
{
|
||||||
|
<li>@line</li>
|
||||||
|
}
|
||||||
|
</ul>
|
||||||
|
<p>Per confermare scrivi la frase qui sotto e la tua password.</p>
|
||||||
|
<label>Conto reale
|
||||||
|
<select name="conto" required>
|
||||||
|
@foreach (var a in accounts)
|
||||||
|
{
|
||||||
|
<option value="@a.Id">@a.Name</option>
|
||||||
|
}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label>Scrivi: <code>@s.Phrase</code><input name="frase" required autocomplete="off" /></label>
|
||||||
|
<label>Password<input name="password" type="password" required autocomplete="current-password" /></label>
|
||||||
|
<label>Codice a sei cifre (se attivo)<input name="codice" inputmode="numeric" autocomplete="one-time-code" /></label>
|
||||||
|
<button class="btn btn-danger" type="submit">Conferma soldi veri</button>
|
||||||
|
</form>
|
||||||
|
</details>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if (s.Stage.Stage == StrategyStages.Simulation && !Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/strategie/@s.Stage.Strategy/osservazione" class="form-inline">
|
||||||
|
<AntiforgeryToken />
|
||||||
|
<button class="btn btn-small" type="submit" data-confirm="Riporta la strategia in osservazione: smette di operare nel simulatore. Confermi?">Riporta in osservazione</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
|
||||||
|
<section class="plain" aria-labelledby="osservazione">
|
||||||
|
<div class="panel-head">
|
||||||
|
<h2 id="osservazione">In osservazione</h2>
|
||||||
|
<a href="/laboratorio">Prova una nuova strategia nel laboratorio</a>
|
||||||
|
</div>
|
||||||
|
@if (watching.Count == 0)
|
||||||
|
{
|
||||||
|
<p class="note">Nessuna strategia di base in osservazione.</p>
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<dl class="observing">
|
||||||
|
@foreach (var s in watching)
|
||||||
|
{
|
||||||
|
var report = StrategiesView.ReportOf(s.Stage);
|
||||||
|
var passed = s.Stage.Qualification?.Passed == true;
|
||||||
|
<dt>@s.Name</dt>
|
||||||
|
<dd>
|
||||||
|
<span>@StrategiesView.ObservationReason(s.Stage)@if (report is not null) {<text> Rapporto: </text><code>@report</code>}</span>
|
||||||
|
@if (passed && !Shell.IsDemo)
|
||||||
|
{
|
||||||
|
<form method="post" action="/azioni/strategie/@s.Stage.Strategy/simulazione"><AntiforgeryToken /><button class="btn btn-small" type="submit">Porta in simulazione</button></form>
|
||||||
|
}
|
||||||
|
else if (!passed)
|
||||||
|
{
|
||||||
|
<span class="attention nowrap"><Icon Name="alert" Size="16" />@(s.Stage.Qualification?.Verdict.Contains("Alpaca", StringComparison.Ordinal) == true ? "In attesa dei dati" : "Non supera i test")</span>
|
||||||
|
}
|
||||||
|
</dd>
|
||||||
|
}
|
||||||
|
</dl>
|
||||||
|
}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
@code {
|
||||||
|
private StrategiesView _view = null!;
|
||||||
|
private string _currency = "EUR";
|
||||||
|
private string? _message;
|
||||||
|
private bool _ok;
|
||||||
|
|
||||||
|
[CascadingParameter]
|
||||||
|
public HttpContext? HttpContext { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "ok")]
|
||||||
|
public string? Ok { get; set; }
|
||||||
|
|
||||||
|
[SupplyParameterFromQuery(Name = "errore")]
|
||||||
|
public string? Errore { get; set; }
|
||||||
|
|
||||||
|
protected override async Task LoadAsync()
|
||||||
|
{
|
||||||
|
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
|
||||||
|
var services = Host.Services!;
|
||||||
|
_currency = Shell.Effective((await services.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value);
|
||||||
|
_view = await StrategiesView.LoadAsync(services, Clock, TradingConsent.From(Host.Config).AllowLive, ct);
|
||||||
|
(_message, _ok) = (Ok, Errore) switch
|
||||||
|
{
|
||||||
|
("simulazione", _) => ("Fatto: la strategia è in simulazione, con ordini finti su prezzi veri.", true),
|
||||||
|
("osservazione", _) => ("Fatto: la strategia è in osservazione.", true),
|
||||||
|
("reale", _) => ("Fatto: la strategia usa soldi veri da adesso. Se peggiora torna indietro da sola.", true),
|
||||||
|
(_, "backtest") => ("Solo una strategia che ha superato il backtest può andare in simulazione.", false),
|
||||||
|
(_, "osservazione-giorni") => ($"Prima della simulazione servono almeno {StageBook.ObservationDays} giorni di segnali raccolti dal vivo in osservazione.", false),
|
||||||
|
(_, "frase") => ("La frase non corrisponde: scrivila esattamente come è mostrata.", false),
|
||||||
|
(_, "password") => ("Password o codice non corretti. Dopo cinque tentativi sbagliati devi aspettare 15 minuti.", false),
|
||||||
|
(_, "requisiti") => ("Non tutti i requisiti sono soddisfatti.", false),
|
||||||
|
(_, "conto") => ("Il conto scelto non è il conto reale del broker di questa strategia.", false),
|
||||||
|
(_, "consenso") => ("La configurazione d'avvio non consente i soldi veri.", false),
|
||||||
|
(_, { }) => ("Non è stato possibile completare la scelta: riprova.", false),
|
||||||
|
_ => (null, false),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string StageText(string stage) => stage switch
|
||||||
|
{
|
||||||
|
StrategyStages.Observation => "Produce solo segnali, nessun ordine.",
|
||||||
|
StrategyStages.Simulation => $"Ordini finti su prezzi veri, per almeno {StageBook.SimulationDays} giorni.",
|
||||||
|
StrategyStages.Reduced => "Soldi veri, con un quarto del capitale.",
|
||||||
|
_ => "Soldi veri, rischio pieno.",
|
||||||
|
};
|
||||||
|
|
||||||
|
private static string Capital(string text) => text.Length == 0 ? text : char.ToUpper(text[0], CultureInfo.GetCultureInfo("it-IT")) + text[1..];
|
||||||
|
|
||||||
|
private static string Css(decimal value) => value.ToString("0.##", CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
@@ -133,6 +133,13 @@ internal static partial class Endpoints
|
|||||||
return Error(StatusCodes.Status400BadRequest, "usa_i_comandi", "Lo stato del bot si cambia con pausa, ripresa e Ferma tutto.");
|
return Error(StatusCodes.Status400BadRequest, "usa_i_comandi", "Lo stato del bot si cambia con pausa, ripresa e Ferma tutto.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Risk limits go only through the settings page, which checks their order and asks for the confirmation of
|
||||||
|
// SPEC 12.4 when a limit goes up while a strategy uses real money: the check holds on the API too.
|
||||||
|
if (Anubis.Risk.RiskSettings.All.Any(d => d.Key == key))
|
||||||
|
{
|
||||||
|
return Error(StatusCodes.Status400BadRequest, "usa_le_impostazioni", "I limiti di rischio si cambiano da Impostazioni, con la conferma quando servono soldi veri.");
|
||||||
|
}
|
||||||
|
|
||||||
return await SetSettingAsync(host, key, body.Value, context, ct).ConfigureAwait(false);
|
return await SetSettingAsync(host, key, body.Value, context, ct).ConfigureAwait(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -156,6 +163,17 @@ internal static partial class Endpoints
|
|||||||
"text/csv; charset=utf-8", $"anubis-posizioni-{day}.csv");
|
"text/csv; charset=utf-8", $"anubis-posizioni-{day}.csv");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// The closed trades of the Operazioni screen as CSV (SPEC 13.6), with the same filters as the page.
|
||||||
|
api.MapGet("/operazioni.csv", async (AnubisHost host, ShellData shell, IClock clock, string? cerca, string? conto, string? strategia, string? esito, string? periodo,
|
||||||
|
CancellationToken ct) =>
|
||||||
|
{
|
||||||
|
var filter = TradeFilter.Parse(cerca, conto, strategia, esito, periodo, null);
|
||||||
|
var view = await TradesView.LoadAsync(host.Services!, clock, filter, int.MaxValue, ct).ConfigureAwait(false);
|
||||||
|
var day = TimeZoneInfo.ConvertTime(clock.UtcNow, shell.Zone).ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
|
||||||
|
return Results.File(System.Text.Encoding.UTF8.GetPreamble().Concat(System.Text.Encoding.UTF8.GetBytes(view.Csv())).ToArray(),
|
||||||
|
"text/csv; charset=utf-8", $"anubis-operazioni-{day}.csv");
|
||||||
|
});
|
||||||
|
|
||||||
// The external sources and the live feed: what is on, what is off and why (SPEC 4.4).
|
// The external sources and the live feed: what is on, what is off and why (SPEC 4.4).
|
||||||
api.MapGet("/data/sources", async (AnubisHost host, IClock clock, CancellationToken ct) =>
|
api.MapGet("/data/sources", async (AnubisHost host, IClock clock, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
@@ -241,12 +259,18 @@ internal static partial class Endpoints
|
|||||||
{
|
{
|
||||||
var settings = host.Services!.Settings;
|
var settings = host.Services!.Settings;
|
||||||
var current = (await settings.GetAsync(SettingsStore.BotState.Key, ct).ConfigureAwait(false)).Value;
|
var current = (await settings.GetAsync(SettingsStore.BotState.Key, ct).ConfigureAwait(false)).Value;
|
||||||
|
|
||||||
|
// A switch tripped by the fall from the high stops only its world and leaves the bot "active": the restart is
|
||||||
|
// the user's confirmation for that world too (SPEC 9.2, 9.3).
|
||||||
|
var tripped = host.Services.Trading?.Risk is { } engine && await engine.AnyTrippedAsync(ct).ConfigureAwait(false);
|
||||||
var target = command switch
|
var target = command switch
|
||||||
{
|
{
|
||||||
"pause" or "pausa" when current == "active" => "paused",
|
"pause" or "pausa" when current == "active" => "paused",
|
||||||
"resume" or "riprendi" when current == "paused" => "active",
|
"resume" or "riprendi" when current == "paused" => "active",
|
||||||
"stop" or "ferma" => "stopped",
|
"stop" or "ferma" => "stopped",
|
||||||
|
"close" or "chiudi" => "stopped",
|
||||||
"restart" or "riattiva" when current == "stopped" => "active",
|
"restart" or "riattiva" when current == "stopped" => "active",
|
||||||
|
"restart" or "riattiva" when tripped => current,
|
||||||
_ => null,
|
_ => null,
|
||||||
};
|
};
|
||||||
if (target is null)
|
if (target is null)
|
||||||
@@ -256,7 +280,33 @@ internal static partial class Endpoints
|
|||||||
: "Comando non ammesso nello stato attuale del bot.");
|
: "Comando non ammesso nello stato attuale del bot.");
|
||||||
}
|
}
|
||||||
|
|
||||||
await settings.SetAsync(SettingsStore.BotState.Key, target, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
var by = context.User.Identity?.Name ?? "utente";
|
||||||
|
if (host.Services.Trading is { Risk: { } risk } trading)
|
||||||
|
{
|
||||||
|
// The switch of SPEC 9.3 goes through the risk engine: it cancels the orders under way and keeps the stops.
|
||||||
|
switch (command)
|
||||||
|
{
|
||||||
|
case "stop" or "ferma":
|
||||||
|
await risk.StopAllAsync(trading.Managers, by, "manual_stop", "Ferma tutto dall'interfaccia: annullo gli ordini in attesa e non apro posizioni. Gli stop restano.", ct)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
return (true, target);
|
||||||
|
case "close" or "chiudi":
|
||||||
|
await risk.CloseAllAsync(trading.Managers, by, ct).ConfigureAwait(false);
|
||||||
|
return (true, target);
|
||||||
|
case "restart" or "riattiva":
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await risk.RestartAsync(by, ct).ConfigureAwait(false);
|
||||||
|
return (true, target);
|
||||||
|
}
|
||||||
|
catch (InvalidOperationException ex)
|
||||||
|
{
|
||||||
|
return (false, ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await settings.SetAsync(SettingsStore.BotState.Key, target, by, ct).ConfigureAwait(false);
|
||||||
return (true, target);
|
return (true, target);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+170
-3
@@ -35,6 +35,9 @@ internal static partial class Forms
|
|||||||
signed.MapPost("/chiavi/{broker}/togli", RemoveKeysAsync);
|
signed.MapPost("/chiavi/{broker}/togli", RemoveKeysAsync);
|
||||||
signed.MapPost("/capitale/{broker}", SetCapitalAsync);
|
signed.MapPost("/capitale/{broker}", SetCapitalAsync);
|
||||||
signed.MapPost("/laboratorio", PlanTrialAsync);
|
signed.MapPost("/laboratorio", PlanTrialAsync);
|
||||||
|
signed.MapPost("/strategie/{strategy}/{choice}", StrategyStageAsync);
|
||||||
|
signed.MapPost("/rischio/limiti", SetLimitsAsync);
|
||||||
|
signed.MapPost("/rischio/{key}", SetRiskSettingAsync);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string Back(IFormCollection form, string fallback)
|
private static string Back(IFormCollection form, string fallback)
|
||||||
@@ -173,8 +176,8 @@ internal static partial class Forms
|
|||||||
private static async Task<IResult> BotAsync(string command, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
private static async Task<IResult> BotAsync(string command, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||||
{
|
{
|
||||||
var back = Back(form, "/");
|
var back = Back(form, "/");
|
||||||
var (ok, _) = await Endpoints.BotCommandAsync(host, command, context, ct).ConfigureAwait(false);
|
var (ok, message) = await Endpoints.BotCommandAsync(host, command, context, ct).ConfigureAwait(false);
|
||||||
return Results.Redirect(ok ? back : With(back, "errore", "bot"));
|
return Results.Redirect(ok ? back : With(back, "errore", message.Contains("STOP", StringComparison.Ordinal) ? "file-stop" : "bot"));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The user's choice for an account in prudent mode after the 15 minutes (SPEC 7.4): align or leave out.</summary>
|
/// <summary>The user's choice for an account in prudent mode after the 15 minutes (SPEC 7.4): align or leave out.</summary>
|
||||||
@@ -291,7 +294,7 @@ internal static partial class Forms
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The capital entrusted to a broker, in euro (SPEC 7.1, 8.6): only the user sets it.</summary>
|
/// <summary>The capital entrusted to a broker, in euro (SPEC 7.1, 8.6): only the user sets it.</summary>
|
||||||
private static async Task<IResult> SetCapitalAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
private static async Task<IResult> SetCapitalAsync(string broker, IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct)
|
||||||
{
|
{
|
||||||
const string back = "/impostazioni";
|
const string back = "/impostazioni";
|
||||||
if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca))
|
if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca))
|
||||||
@@ -309,6 +312,13 @@ internal static partial class Forms
|
|||||||
return Results.Redirect(back + "?errore=importo#conti");
|
return Results.Redirect(back + "?errore=importo#conti");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// More capital while a strategy of this broker has real money is more risk: it needs the procedure (SPEC 12.4).
|
||||||
|
if ((await trading.Capital.EntrustedAsync(broker, ct).ConfigureAwait(false))?.AmountEur is { } before && amount > before &&
|
||||||
|
await RaiseRefusalAsync(host.Services!, clock, broker, form, ct).ConfigureAwait(false) is { } refusal)
|
||||||
|
{
|
||||||
|
return Results.Redirect(back + "?errore=" + refusal + "#conti");
|
||||||
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await trading.SetCapitalAsync(broker, amount, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
await trading.SetCapitalAsync(broker, amount, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
||||||
@@ -325,6 +335,163 @@ internal static partial class Forms
|
|||||||
return Results.Redirect(back + "?ok=capitale#conti");
|
return Results.Redirect(back + "?ok=capitale#conti");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The user's choices on the Strategie screen (SPEC 12.3, 12.4): observation and simulation from a button, real
|
||||||
|
/// money only through the procedure, with the phrase, the password and the second factor checked by the stage book.
|
||||||
|
/// </summary>
|
||||||
|
private static async Task<IResult> StrategyStageAsync(string strategy, string choice, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (host.IsDemo || host.Services is not { } services || !Anubis.Trading.StrategyNames.Base.Any(b => b.Name == strategy))
|
||||||
|
{
|
||||||
|
return Results.Redirect("/strategie?errore=scelta");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (services.Trading?.Stages is not { } stages)
|
||||||
|
{
|
||||||
|
return Results.Redirect("/strategie?errore=motore");
|
||||||
|
}
|
||||||
|
|
||||||
|
var by = context.User.Identity?.Name ?? "utente";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
switch (choice)
|
||||||
|
{
|
||||||
|
case "simulazione":
|
||||||
|
var stage = await stages.GetAsync(strategy, ct).ConfigureAwait(false);
|
||||||
|
if (stage?.Qualification is not { Passed: true })
|
||||||
|
{
|
||||||
|
// A strategy that did not pass its backtest stays in observation (SPEC 12.3).
|
||||||
|
return Results.Redirect("/strategie?errore=backtest");
|
||||||
|
}
|
||||||
|
|
||||||
|
await stages.MoveAsync(strategy, Anubis.Trading.StrategyStages.Simulation, "user", by, ct).ConfigureAwait(false);
|
||||||
|
return Results.Redirect("/strategie?ok=simulazione");
|
||||||
|
case "osservazione":
|
||||||
|
var current = await stages.GetAsync(strategy, ct).ConfigureAwait(false);
|
||||||
|
if (current is not null && Anubis.Trading.StrategyStages.IsLive(current.Stage))
|
||||||
|
{
|
||||||
|
await stages.RevokeAsync(strategy, by, "user", ct).ConfigureAwait(false);
|
||||||
|
return Results.Redirect("/strategie?ok=simulazione");
|
||||||
|
}
|
||||||
|
|
||||||
|
await stages.MoveAsync(strategy, Anubis.Trading.StrategyStages.Observation, "user", by, ct).ConfigureAwait(false);
|
||||||
|
return Results.Redirect("/strategie?ok=osservazione");
|
||||||
|
case "reale" when Guid.TryParse(form["conto"].ToString(), out var account):
|
||||||
|
var code = form["codice"].ToString();
|
||||||
|
await stages.ConfirmLiveAsync(new Anubis.Trading.LiveConfirmation(strategy, account, form["frase"].ToString(), form["password"].ToString(),
|
||||||
|
string.IsNullOrWhiteSpace(code) ? null : code.Trim(), by), ct).ConfigureAwait(false);
|
||||||
|
return Results.Redirect("/strategie?ok=reale");
|
||||||
|
default:
|
||||||
|
return Results.Redirect("/strategie?errore=scelta");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Anubis.Trading.LiveConfirmationException ex)
|
||||||
|
{
|
||||||
|
var error = ex.Code switch
|
||||||
|
{
|
||||||
|
"phrase" => "frase",
|
||||||
|
"password" => "password",
|
||||||
|
"requirements" => "requisiti",
|
||||||
|
"backtest" => "backtest",
|
||||||
|
"observation" => "osservazione-giorni",
|
||||||
|
"account" => "conto",
|
||||||
|
Anubis.Risk.RiskReasons.NoConsent => "consenso",
|
||||||
|
_ => "scelta",
|
||||||
|
};
|
||||||
|
return Results.Redirect("/strategie?errore=" + error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The risk limits (SPEC 9.2, 13.5), all at once. Lowering is always allowed; raising any of them while a strategy
|
||||||
|
/// has real money needs the phrase, the password and the second factor (SPEC 12.4).
|
||||||
|
/// </summary>
|
||||||
|
private static async Task<IResult> SetLimitsAsync(IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct)
|
||||||
|
{
|
||||||
|
const string back = "/impostazioni";
|
||||||
|
if (host.IsDemo || host.Services is not { } services)
|
||||||
|
{
|
||||||
|
return Results.Redirect(back + "?errore=motore#rischio");
|
||||||
|
}
|
||||||
|
|
||||||
|
var current = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||||
|
var next = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||||
|
foreach (var definition in Anubis.Risk.RiskSettings.Limits)
|
||||||
|
{
|
||||||
|
current[definition.Key] = (await services.Settings.GetAsync(definition.Key, ct).ConfigureAwait(false)).Value;
|
||||||
|
var typed = form[definition.Key].ToString().Trim().Replace(',', '.');
|
||||||
|
if (typed.Length == 0)
|
||||||
|
{
|
||||||
|
next[definition.Key] = current[definition.Key];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (definition.Check?.Invoke(typed) is not null)
|
||||||
|
{
|
||||||
|
return Results.Redirect(back + "?errore=limite#rischio");
|
||||||
|
}
|
||||||
|
|
||||||
|
next[definition.Key] = typed;
|
||||||
|
}
|
||||||
|
|
||||||
|
var limits = Anubis.Risk.RiskSettings.From(k => next[k]);
|
||||||
|
if (limits.DrawdownHalf >= limits.DrawdownStop || limits.DailyLoss > limits.WeeklyLoss)
|
||||||
|
{
|
||||||
|
return Results.Redirect(back + "?errore=ordine-limiti#rischio");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Anubis.Risk.RiskSettings.From(k => current[k]).RaisedBy(limits))
|
||||||
|
{
|
||||||
|
if (await RaiseRefusalAsync(services, clock, null, form, ct).ConfigureAwait(false) is { } refusal)
|
||||||
|
{
|
||||||
|
return Results.Redirect(back + "?errore=" + refusal + "#rischio");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var by = context.User.Identity?.Name ?? "utente";
|
||||||
|
foreach (var (key, value) in next.Where(n => n.Value != current[n.Key]))
|
||||||
|
{
|
||||||
|
await services.Settings.SetAsync(key, value, by, ct).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Results.Redirect(back + "?ok=limiti#rischio");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The day-trade guard and the scenarios of the Rischio screen: they change no limit, so no procedure.</summary>
|
||||||
|
private static async Task<IResult> SetRiskSettingAsync(string key, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
||||||
|
{
|
||||||
|
const string back = "/impostazioni";
|
||||||
|
if (key != Anubis.Risk.RiskSettings.PdtGuard.Key && key != Anubis.Risk.Scenarios.Setting.Key)
|
||||||
|
{
|
||||||
|
return Results.Redirect(back + "?errore=impostazione#rischio");
|
||||||
|
}
|
||||||
|
|
||||||
|
var result = await Endpoints.SetSettingAsync(host, key, form["valore"].ToString(), context, ct).ConfigureAwait(false);
|
||||||
|
return Results.Redirect(result is IStatusCodeHttpResult { StatusCode: StatusCodes.Status204NoContent } ? back + "?ok=rischio#rischio" : back + "?errore=scenari#rischio");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Null when more risk may go ahead; otherwise the error code for the page.</summary>
|
||||||
|
private static async Task<string?> RaiseRefusalAsync(AppServices services, IClock clock, string? broker, IFormCollection form, CancellationToken ct)
|
||||||
|
{
|
||||||
|
// Without the trading engine no strategy can hold real money, so the stage book only has to say so.
|
||||||
|
var stages = services.Trading?.Stages ?? new Anubis.Trading.StageBook(services.Db, clock, Anubis.Trading.TradingConsent.None, (_, _, _) => Task.FromResult(false));
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var code = form["codice"].ToString();
|
||||||
|
await stages.ConfirmRaiseAsync(broker, form["frase"].ToString(), form["password"].ToString(), string.IsNullOrWhiteSpace(code) ? null : code.Trim(), ct).ConfigureAwait(false);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
catch (Anubis.Trading.LiveConfirmationException ex)
|
||||||
|
{
|
||||||
|
return ex.Code switch
|
||||||
|
{
|
||||||
|
"phrase" => "frase-rischio",
|
||||||
|
"demotion" => "retrocessione-rischio",
|
||||||
|
_ => "password-rischio",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// A new backtest trial (SPEC 12.2): the plan is written and queued at once, then the page of the trial follows it.
|
/// A new backtest trial (SPEC 12.2): the plan is written and queued at once, then the page of the trial follows it.
|
||||||
/// A field that cannot be read goes back as a code; the chosen strategy is kept, nothing typed travels in the address.
|
/// A field that cannot be read goes back as a code; the chosen strategy is kept, nothing typed travels in the address.
|
||||||
|
|||||||
@@ -83,6 +83,8 @@ internal static class LabText
|
|||||||
BacktestReasons.NoShortSelling => "Vendite allo scoperto rifiutate",
|
BacktestReasons.NoShortSelling => "Vendite allo scoperto rifiutate",
|
||||||
BacktestReasons.WrittenOff => "Residui sotto il minimo lasciati dopo un'uscita",
|
BacktestReasons.WrittenOff => "Residui sotto il minimo lasciati dopo un'uscita",
|
||||||
BacktestReasons.Dividend => "Dividendi incassati",
|
BacktestReasons.Dividend => "Dividendi incassati",
|
||||||
|
_ when reason.StartsWith(BacktestReasons.AdjustedPrefix, StringComparison.Ordinal) =>
|
||||||
|
"Decisioni cambiate da correttivi e rischio (" + ReasonTexts.Text(reason[BacktestReasons.AdjustedPrefix.Length..]).TrimEnd('.') + ")",
|
||||||
_ => "Ordini sotto il minimo dello strumento, non inviati",
|
_ => "Ordini sotto il minimo dello strumento, non inviati",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -12,6 +12,12 @@ if (args.Length >= 1 && args[0] == "data")
|
|||||||
return await DataCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
return await DataCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// "anubis backtest base": the honest backtests of the base strategies, written to docs/backtests (Phase 5).
|
||||||
|
if (args.Length >= 1 && args[0] == "backtest")
|
||||||
|
{
|
||||||
|
return await BacktestCommand.RunAsync(args[1..]).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
var app = ServerApp.Build(args);
|
var app = ServerApp.Build(args);
|
||||||
await app.RunAsync().ConfigureAwait(false);
|
await app.RunAsync().ConfigureAwait(false);
|
||||||
return 0;
|
return 0;
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Server;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The fixed templates that turn the reason codes of the decisions table into plain Italian (SPEC 5.2): the "why"
|
||||||
|
/// card of a trade and the diary use these, never free text written at decision time. An unknown code is shown as
|
||||||
|
/// it is, so nothing is ever hidden.
|
||||||
|
/// </summary>
|
||||||
|
internal static class ReasonTexts
|
||||||
|
{
|
||||||
|
private static readonly Dictionary<string, string> Texts = new(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
// Strategies.
|
||||||
|
["trend_entry"] = "La chiusura ha superato i massimi recenti su almeno un orizzonte: è iniziata una tendenza al rialzo.",
|
||||||
|
["trend_increase"] = "Più orizzonti erano d'accordo sulla tendenza: il peso è salito.",
|
||||||
|
["trend_reduce"] = "La tendenza si è indebolita, o la moneta è diventata più agitata: il peso è sceso.",
|
||||||
|
["trend_exit"] = "La tendenza si è interrotta: il prezzo è finito sotto lo stop mobile.",
|
||||||
|
["trend_stop"] = "Lo stop mobile è salito con il prezzo.",
|
||||||
|
["momentum_entry"] = "Era tra i titoli più forti degli ultimi mesi, con il mercato in salita.",
|
||||||
|
["momentum_increase"] = "Il peso obiettivo è salito alla revisione settimanale.",
|
||||||
|
["momentum_reduce"] = "Il peso obiettivo è sceso alla revisione settimanale.",
|
||||||
|
["momentum_exit_rank"] = "Non era più tra i 30 titoli più forti.",
|
||||||
|
["momentum_exit_trend"] = "Il mercato nel suo insieme è girato al ribasso: niente più azioni.",
|
||||||
|
["momentum_stop"] = "Lo stop di protezione è stato aggiornato.",
|
||||||
|
["meanrev_entry"] = "Era sceso per qualche seduta di fila ma restava sopra la sua media a 200 giorni: un ribasso breve di un titolo che nel lungo periodo sale.",
|
||||||
|
["meanrev_exit_average"] = "Il prezzo è tornato sopra la media a 5 giorni: il rimbalzo cercato è arrivato.",
|
||||||
|
["meanrev_exit_rsi"] = "L'indicatore di forza è tornato alto: il rimbalzo è avvenuto.",
|
||||||
|
["meanrev_exit_earnings"] = "Uscita prima della trimestrale.",
|
||||||
|
["meanrev_exit_time"] = "Tempo scaduto: nessun rimbalzo in 5 sedute.",
|
||||||
|
// Exits recorded on the trade.
|
||||||
|
["stop"] = "Stop di protezione raggiunto.",
|
||||||
|
["exit"] = "Uscita decisa dalla strategia.",
|
||||||
|
["signal"] = "Uscita sul segnale della strategia.",
|
||||||
|
["residue"] = "Resto troppo piccolo per essere venduto, tolto dal registro.",
|
||||||
|
["adjustment"] = "Rettifica dopo l'allineamento con il conto.",
|
||||||
|
// Correctives.
|
||||||
|
["crypto_regime_below_average"] = "Il mercato crypto era sotto la sua media: acquisti ridotti.",
|
||||||
|
["crypto_regime_high_volatility"] = "Il mercato crypto era molto agitato: acquisti ridotti.",
|
||||||
|
["calendar_event"] = "Un dato economico importante era vicino: niente nuove posizioni in quell'ora.",
|
||||||
|
// Risk.
|
||||||
|
["risk_reduction"] = "Ordine rimpicciolito dai limiti di rischio.",
|
||||||
|
["daily_loss_block"] = "Perdita del giorno oltre il limite: niente nuovi ingressi per 24 ore.",
|
||||||
|
["switch_tripped"] = "Interruttore scattato: il bot aspetta la tua conferma.",
|
||||||
|
["bot_paused"] = "Bot in pausa: niente nuovi ingressi.",
|
||||||
|
["bot_stopped"] = "Bot fermato con \"Ferma tutto\".",
|
||||||
|
["invested_limit"] = "Capitale investito al limite: niente soldi presi in prestito.",
|
||||||
|
["position_limit"] = "Ridotto al peso massimo di una posizione.",
|
||||||
|
["crypto_limit"] = "Quota delle crypto sul totale al limite.",
|
||||||
|
["trade_risk_limit"] = "Ridotto perché il rischio dell'operazione restasse entro il limite.",
|
||||||
|
["stop_above_price"] = "Stop sopra il prezzo: ordine rifiutato.",
|
||||||
|
["stale_price"] = "Prezzo troppo vecchio: niente acquisti finché i dati non tornano freschi.",
|
||||||
|
["price_gap"] = "Prezzo dell'ordine troppo lontano dall'ultimo prezzo.",
|
||||||
|
["clock_skew"] = "Orologio non allineato con quello del broker.",
|
||||||
|
["owned_by_other_strategy"] = "La posizione appartiene a un'altra strategia.",
|
||||||
|
["no_short_selling"] = "Niente vendite allo scoperto: venduto solo quanto posseduto.",
|
||||||
|
["no_leverage"] = "Niente leva: l'ordine sta nella liquidità disponibile.",
|
||||||
|
["not_owned_by_bot"] = "La posizione non è del bot: non la tocca.",
|
||||||
|
["live_not_confirmed"] = "Soldi veri non confermati per questa strategia.",
|
||||||
|
["exit_only"] = "Strategia in sola uscita: niente nuovi acquisti.",
|
||||||
|
["live_not_allowed"] = "Soldi veri non permessi dalla configurazione d'avvio.",
|
||||||
|
["observation"] = "Strategia in osservazione: produce segnali, nessun ordine.",
|
||||||
|
["orders_per_minute"] = "Troppi ordini in un minuto: il bot si è fermato.",
|
||||||
|
["pdt_guard"] = "Guardia sulle operazioni in giornata: niente posizioni in più oggi.",
|
||||||
|
["no_fx_rate"] = "Manca il cambio euro-dollaro: niente acquisti in dollari.",
|
||||||
|
["unknown_instrument"] = "Strumento sconosciuto.",
|
||||||
|
};
|
||||||
|
|
||||||
|
// The exits in the few words of a table column; the full sentence stays for the "why" card.
|
||||||
|
private static readonly Dictionary<string, string> ShortExits = new(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
["trend_exit"] = "La tendenza si è interrotta: prezzo sotto lo stop mobile",
|
||||||
|
["momentum_exit_rank"] = "Non era più tra i 30 titoli più forti",
|
||||||
|
["momentum_exit_trend"] = "Il mercato è girato al ribasso",
|
||||||
|
["meanrev_exit_average"] = "Tornata sopra la media a 5 giorni",
|
||||||
|
["meanrev_exit_rsi"] = "Rimbalzo arrivato: forza tornata alta",
|
||||||
|
["meanrev_exit_earnings"] = "Uscita prima della trimestrale",
|
||||||
|
["meanrev_exit_time"] = "Tempo scaduto: nessun rimbalzo in 5 sedute",
|
||||||
|
["stop"] = "Stop di protezione raggiunto",
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>Why a trade was closed, in a short sentence.</summary>
|
||||||
|
public static string Exit(string? code) => code is null ? "Chiusa" : ShortExits.TryGetValue(code, out var text) ? text : Text(code).TrimEnd('.');
|
||||||
|
|
||||||
|
public static string Text(string code) => Texts.TryGetValue(code, out var text) ? text : code;
|
||||||
|
|
||||||
|
/// <summary>The lines of one stage of a decision. <paramref name="data"/> is the JSON of the numbers the stage used.</summary>
|
||||||
|
public static IEnumerable<WhyLine> Stage(string stage, string outcome, IReadOnlyList<string> reasons, string? data)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(reasons);
|
||||||
|
var good = outcome is DecisionOutcomes.Passed or DecisionOutcomes.Proposed or DecisionOutcomes.Same;
|
||||||
|
if (stage == DecisionStages.Risk && outcome == DecisionOutcomes.Passed && reasons.Count == 0)
|
||||||
|
{
|
||||||
|
yield return new WhyLine("Tutti i limiti di rischio rispettati" + Asked(data), true);
|
||||||
|
yield break;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var reason in reasons)
|
||||||
|
{
|
||||||
|
yield return new WhyLine(Text(reason).TrimEnd('.') + (stage == DecisionStages.Risk ? Asked(data) : ""), good || stage == DecisionStages.Strategy);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// "(chiesti 0,05, passati 0,03)" when the stage shrank the order.
|
||||||
|
private static string Asked(string? data)
|
||||||
|
{
|
||||||
|
if (data is null)
|
||||||
|
{
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
using var json = JsonDocument.Parse(data);
|
||||||
|
if (json.RootElement.TryGetProperty("asked", out var asked) && json.RootElement.TryGetProperty("allowed", out var allowed) &&
|
||||||
|
asked.TryGetDecimal(out var a) && allowed.TryGetDecimal(out var b) && b < a)
|
||||||
|
{
|
||||||
|
return $" (chiesti {Format.Quantity(a)}, passati {Format.Quantity(b)})";
|
||||||
|
}
|
||||||
|
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Risk;
|
||||||
|
using Anubis.Strategies;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Server;
|
||||||
|
|
||||||
|
/// <summary>A row of the limits table: what is used now against the threshold, and what happens beyond it.</summary>
|
||||||
|
internal sealed record LimitRow(string Label, string Now, string? Detail, decimal? Usage, string Threshold, string Beyond, string Key);
|
||||||
|
|
||||||
|
/// <summary>A point of the fall from the high, as a fraction: 0 at the high, −0,03 three percent below.</summary>
|
||||||
|
internal sealed record DrawdownPoint(DateTimeOffset At, decimal Drawdown);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The Rischio screen (SPEC 9, 13.6, mockup 07): the emergency switch, the automatic blocks, the limits with what
|
||||||
|
/// they use now, the fall from the high, the scenarios and the risk events. One world, as on Conti.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed record RiskView(
|
||||||
|
string BotState,
|
||||||
|
bool StopFile,
|
||||||
|
bool CloseAllPending,
|
||||||
|
string World,
|
||||||
|
WorldRisk Risk,
|
||||||
|
RiskLimits Limits,
|
||||||
|
IReadOnlyList<LimitRow> Rows,
|
||||||
|
IReadOnlyList<DrawdownPoint> Drawdown,
|
||||||
|
IReadOnlyList<ScenarioResult> Scenarios,
|
||||||
|
IReadOnlyList<(DateTimeOffset At, string Kind, string Severity, string Message, string? World)> Events,
|
||||||
|
(DateTimeOffset From, DateTimeOffset To, string Title)? NextCalendarBlock,
|
||||||
|
(DateTimeOffset From, DateTimeOffset To, string Title)? LastCalendarBlock,
|
||||||
|
bool PdtGuard,
|
||||||
|
bool HasPositions,
|
||||||
|
IReadOnlyList<WorldRisk> Tripped)
|
||||||
|
{
|
||||||
|
public bool AnyBlock => Tripped.Count > 0 || Risk.EntriesBlocked || Risk.Multiplier < 1m || BotState != "active";
|
||||||
|
|
||||||
|
/// <summary>The switch tripped by itself in a world (SPEC 9.2): it waits for the user's restart, like "Ferma tutto".</summary>
|
||||||
|
public bool WaitsForRestart => BotState == "stopped" || Tripped.Count > 0;
|
||||||
|
|
||||||
|
public static async Task<RiskView> LoadAsync(AppServices services, IClock clock, TimeZoneInfo zone, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(services);
|
||||||
|
var engine = services.Trading?.Risk ?? new RiskEngine(services.Db, clock, new Ledger(services.Db, clock),
|
||||||
|
new StageBook(services.Db, clock, TradingConsent.None, (_, _, _) => Task.FromResult(false)), services.Settings, new FxStore(services.Db, clock),
|
||||||
|
(_, _) => Task.FromResult<Instrument?>(null), (_, _) => Task.FromResult<Quote?>(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<WorldRisk>();
|
||||||
|
foreach (var w in new[] { Worlds.Real, Worlds.Simulated })
|
||||||
|
{
|
||||||
|
var each = w == world ? risk : await engine.WorldAsync(w, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (each.State.Tripped)
|
||||||
|
{
|
||||||
|
tripped.Add(each);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Weights, crypto and the risk of a trade are measured on the reference equity, as the risk engine does (SPEC 9.2).
|
||||||
|
var reference = await engine.ReferenceAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
var bot = (await services.Settings.GetAsync(SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value;
|
||||||
|
var now = clock.UtcNow;
|
||||||
|
|
||||||
|
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<LimitRow>
|
||||||
|
{
|
||||||
|
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<DrawdownPoint>();
|
||||||
|
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<IndexPoint> 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
using Anubis.Backtest;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Strategies;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Server;
|
||||||
|
|
||||||
|
/// <summary>A strategy of the Strategie screen: its stage, results, requirements and what the user can do next.</summary>
|
||||||
|
internal sealed record StrategyCard(
|
||||||
|
StrategyStage Stage,
|
||||||
|
string Name,
|
||||||
|
string Description,
|
||||||
|
IReadOnlyList<string> Rules,
|
||||||
|
string Account,
|
||||||
|
string Currency,
|
||||||
|
decimal CapitalEur,
|
||||||
|
decimal ResultEur,
|
||||||
|
decimal ResultPercent,
|
||||||
|
decimal WorstFall,
|
||||||
|
int Closed,
|
||||||
|
int Winners,
|
||||||
|
IReadOnlyList<string> Open,
|
||||||
|
IReadOnlyList<(DateTimeOffset At, decimal Index)> Curve,
|
||||||
|
IReadOnlyList<Requirement> Requirements,
|
||||||
|
string Phrase,
|
||||||
|
int? DaysToGo,
|
||||||
|
IReadOnlyList<string> Summary,
|
||||||
|
decimal? TwinGap)
|
||||||
|
{
|
||||||
|
public string Color => "var(--s-" + Stage.Strategy.Replace('_', '-') + ")";
|
||||||
|
|
||||||
|
public bool AllMet => Requirements.All(r => r.Met);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
internal sealed record StrategiesView(IReadOnlyList<StrategyCard> Cards, bool LiveAllowed, IReadOnlyList<(Guid Id, string Name, string Broker)> LiveAccounts)
|
||||||
|
{
|
||||||
|
/// <summary>What each base strategy does, in four lines (SPEC 8).</summary>
|
||||||
|
public static readonly IReadOnlyDictionary<string, IReadOnlyList<string>> Rules = new Dictionary<string, IReadOnlyList<string>>(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<StrategiesView> 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<string> SymbolAsync(Guid instrument) =>
|
||||||
|
await services.Db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT symbol FROM instruments WHERE id = @id", r => r.Text("symbol"), ("id", instrument)), cancellationToken)
|
||||||
|
.ConfigureAwait(false) ?? "?";
|
||||||
|
var cards = new List<StrategyCard>();
|
||||||
|
foreach (var stage in await stages.AllAsync(cancellationToken).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
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<string>();
|
||||||
|
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<string>();
|
||||||
|
if (stage.Stage is StrategyStages.Simulation or StrategyStages.Reduced)
|
||||||
|
{
|
||||||
|
var toReduced = stage.Stage == StrategyStages.Simulation;
|
||||||
|
var factor = toReduced ? StrategyStages.ReducedShare : 1m;
|
||||||
|
var simEquity = equities.FirstOrDefault(e => e.AccountId == stage.AccountId && e.Strategy == stage.Strategy);
|
||||||
|
var simUsd = accounts.FirstOrDefault(a => a.Id == stage.AccountId).Currency == "USD";
|
||||||
|
decimal SimEur(decimal amount) => simUsd ? (rate > 0m ? amount / rate : 0m) : amount;
|
||||||
|
summary.Add(toReduced
|
||||||
|
? $"Capitale usato: un quarto di quello assegnato, {Format.Money(SimEur(simEquity?.Flows ?? 0m) * factor, decimals: 0)}."
|
||||||
|
: $"Capitale usato: tutto quello assegnato, {Format.Money(SimEur(simEquity?.Flows ?? 0m), decimals: 0)}.");
|
||||||
|
var buys = new List<string>();
|
||||||
|
foreach (var p in positions.Where(p => p.AccountId == stage.AccountId && p.Strategy == stage.Strategy && p.Quantity > 0m))
|
||||||
|
{
|
||||||
|
buys.Add($"{await SymbolAsync(p.InstrumentId).ConfigureAwait(false)} per circa {Format.Money(SimEur(p.Value) * factor, decimals: 0)}");
|
||||||
|
}
|
||||||
|
|
||||||
|
summary.Add(buys.Count == 0
|
||||||
|
? "Acquisti al primo ciclo: nessuno per ora, la simulazione non tiene posizioni."
|
||||||
|
: (toReduced ? "Acquisti al primo ciclo, stimati da ciò che la simulazione tiene oggi: " : "Al primo ciclo le posizioni vere crescono fino alla misura piena: ") +
|
||||||
|
string.Join(", ", buys) + ".");
|
||||||
|
summary.Add("Limiti che valgono: perdita in un giorno " + Format.Percent(limits.DailyLoss * 100m, 1) + ", calo dal massimo " +
|
||||||
|
Format.Percent(limits.DrawdownHalf * 100m, 0) + " e " + Format.Percent(limits.DrawdownStop * 100m, 0) + ", una posizione " +
|
||||||
|
Format.Percent(limits.MaxPosition * 100m, 0) + ", rischio di un'operazione " + Format.Percent(limits.MaxTradeRisk * 100m, 1) +
|
||||||
|
", misurati sul patrimonio di riferimento" + (reference is { } r ? $" (oggi {Format.Money(r, decimals: 0)})" : "") +
|
||||||
|
(toReduced ? ", e in reale ridotto su un quarto di esso." : "."));
|
||||||
|
}
|
||||||
|
|
||||||
|
// The simulated twin against the real account (SPEC 12.3): the gap of results, as a share of the capital used.
|
||||||
|
decimal? twinGap = null;
|
||||||
|
if (stage.HasTwin && stage.AccountId is { } twinAccount &&
|
||||||
|
equities.FirstOrDefault(e => e.AccountId == twinAccount && e.Strategy == stage.Strategy) is { Flows: > 0m } twin && equity is { Flows: > 0m } real)
|
||||||
|
{
|
||||||
|
twinGap = ((real.Equity - real.Flows) / real.Flows * 100m) - ((twin.Equity - twin.Flows) / twin.Flows * 100m);
|
||||||
|
}
|
||||||
|
|
||||||
|
var requirements = await stages.RequirementsAsync(stage.Strategy, cancellationToken).ConfigureAwait(false);
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A requirement not met yet only because time has to pass or nothing could be measured so far.</summary>
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Why a strategy is in observation, in words: the outcome of its backtest, or the user's choice.</summary>
|
||||||
|
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) + ".",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The report of a strategy's backtest in the repository, for the link.</summary>
|
||||||
|
public static string? ReportOf(StrategyStage stage) => stage.Qualification?.Report ?? BacktestOutcomes.Find(stage.Strategy)?.Report;
|
||||||
|
}
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Text;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Server;
|
||||||
|
|
||||||
|
/// <summary>The filters of the Operazioni screen, read from the address so a filtered page can be bookmarked.</summary>
|
||||||
|
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);
|
||||||
|
|
||||||
|
/// <summary>The query string of this filter with one value changed.</summary>
|
||||||
|
public string Query(int? page = null)
|
||||||
|
{
|
||||||
|
var parts = new List<string>();
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A step of the "why" card: a stage of a decision in plain Italian.</summary>
|
||||||
|
internal sealed record WhyLine(string Text, bool Good);
|
||||||
|
|
||||||
|
/// <summary>A closed trade of the Operazioni screen, in its own currency and in euro.</summary>
|
||||||
|
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,
|
||||||
|
IReadOnlyList<WhyLine> Bought, IReadOnlyList<WhyLine> Sold, decimal? EntrySlipBp, decimal? ExitSlipBp)
|
||||||
|
{
|
||||||
|
public decimal Percent => EntryPrice * Quantity == 0m ? 0m : Realized / (EntryPrice * Quantity) * 100m;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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).
|
||||||
|
/// </summary>
|
||||||
|
internal sealed record TradesView(
|
||||||
|
IReadOnlyList<TradeRow> Rows,
|
||||||
|
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<string> Strategies)
|
||||||
|
{
|
||||||
|
public int Losers => Matching - Winners;
|
||||||
|
|
||||||
|
/// <summary>Euro gained for each euro lost: null while nothing was lost.</summary>
|
||||||
|
public decimal? PerEuroLost => Losses < 0m ? Gains / -Losses : null;
|
||||||
|
|
||||||
|
public decimal Net => Gains + Losses;
|
||||||
|
|
||||||
|
public static async Task<TradesView> LoadAsync(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<TradeRow>();
|
||||||
|
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)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The trades as CSV for an Italian spreadsheet: semicolons, decimal commas, one row per closed trade.</summary>
|
||||||
|
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);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
private static async Task<(List<WhyLine> Bought, List<WhyLine> 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<WhyLine> 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<List<string>>(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<List<string>>(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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 IdleTimeout = TimeSpan.FromHours(12);
|
||||||
public static readonly TimeSpan MaxLifetime = TimeSpan.FromDays(7);
|
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.
|
// Each second-factor code works once (RFC 6238, 5.2): the last time step used, in memory.
|
||||||
private readonly Lock _stepGate = new();
|
private readonly Lock _stepGate = new();
|
||||||
private long _lastStep = long.MinValue;
|
private long _lastStep = long.MinValue;
|
||||||
@@ -306,6 +310,34 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets,
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The fresh re-authentication of SPEC 12.4: the password and, when it is on, a code from the app, checked right
|
||||||
|
/// now whatever the session. Nothing is written. After five wrong attempts in 15 minutes every attempt fails,
|
||||||
|
/// even with the right password, until the window has passed.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<bool> ReauthenticateAsync(string password, string? code, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
if (_fresh.Begin(FreshAttempts) > TimeSpan.Zero)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var user = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT id, password_hash, totp_secret FROM users WHERE username = @u",
|
||||||
|
r => (Id: r.Id("id"), Hash: r.Text("password_hash"), Totp: r.BytesOrNull("totp_secret")), ("u", AdminName)), cancellationToken).ConfigureAwait(false);
|
||||||
|
if (user == default || string.IsNullOrEmpty(password) || !Passwords.Verify(password, user.Hash))
|
||||||
|
{
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Turning the second factor off asks for both: the password and a code from the app.</summary>
|
/// <summary>Turning the second factor off asks for both: the password and a code from the app.</summary>
|
||||||
public async Task<bool> DisableSecondFactorAsync(Guid userId, string password, string? code, CancellationToken cancellationToken = default)
|
public async Task<bool> DisableSecondFactorAsync(Guid userId, string password, string? code, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -10,6 +10,8 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<EmbeddedResource Include="Db\Migrations\*.sql" LogicalName="Anubis.Db.Migrations.%(Filename)%(Extension)" />
|
<EmbeddedResource Include="Db\Migrations\*.sql" LogicalName="Anubis.Db.Migrations.%(Filename)%(Extension)" />
|
||||||
<EmbeddedResource Include="Demo\Data\*" LogicalName="Anubis.Demo.Data.%(Filename)%(Extension)" />
|
<EmbeddedResource Include="Demo\Data\*" LogicalName="Anubis.Demo.Data.%(Filename)%(Extension)" />
|
||||||
|
<!-- The backtest outcomes travel with the code (SPEC 12.3): read at the first start. -->
|
||||||
|
<EmbeddedResource Include="..\..\docs\backtests\*.outcome.json" LogicalName="Anubis.Backtests.%(Filename)%(Extension)" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<InternalsVisibleTo Include="Anubis.Tests" />
|
<InternalsVisibleTo Include="Anubis.Tests" />
|
||||||
|
|||||||
@@ -102,14 +102,20 @@ public sealed class BacktestDataset
|
|||||||
{
|
{
|
||||||
private readonly Dictionary<string, BacktestInstrument> _bySymbol;
|
private readonly Dictionary<string, BacktestInstrument> _bySymbol;
|
||||||
|
|
||||||
public BacktestDataset(IEnumerable<BacktestInstrument> instruments, string currency)
|
/// <param name="instruments">Every instrument, the tradable ones and those used only as data.</param>
|
||||||
|
/// <param name="currency">The one currency of the backtest.</param>
|
||||||
|
/// <param name="calendar">The market's sessions, which may go beyond the bars; null means the days with bars.</param>
|
||||||
|
/// <param name="dataOnly">Instruments the strategy reads but never trades, such as SPY for the market filter.</param>
|
||||||
|
public BacktestDataset(IEnumerable<BacktestInstrument> instruments, string currency, IEnumerable<DateOnly>? calendar = null, IEnumerable<string>? dataOnly = null)
|
||||||
{
|
{
|
||||||
ArgumentNullException.ThrowIfNull(instruments);
|
ArgumentNullException.ThrowIfNull(instruments);
|
||||||
Instruments = [.. instruments.OrderBy(i => i.Symbol, StringComparer.Ordinal)];
|
Instruments = [.. instruments.OrderBy(i => i.Symbol, StringComparer.Ordinal)];
|
||||||
Currency = currency;
|
Currency = currency;
|
||||||
_bySymbol = Instruments.ToDictionary(i => i.Symbol, StringComparer.Ordinal);
|
_bySymbol = Instruments.ToDictionary(i => i.Symbol, StringComparer.Ordinal);
|
||||||
Sessions = [.. Instruments.SelectMany(i => i.Bars.Select(b => b.Day)).Distinct().Order()];
|
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<string>(dataOnly ?? [], StringComparer.Ordinal);
|
||||||
|
var wrong = Instruments.FirstOrDefault(i => i.Spec.QuoteCurrency != currency && !DataOnly.Contains(i.Symbol));
|
||||||
if (wrong is not null)
|
if (wrong is not null)
|
||||||
{
|
{
|
||||||
throw new ArgumentException($"{wrong.Symbol} is in {wrong.Spec.QuoteCurrency}, the backtest is in {currency}", nameof(instruments));
|
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<BacktestInstrument> Instruments { get; }
|
public IReadOnlyList<BacktestInstrument> Instruments { get; }
|
||||||
|
|
||||||
|
/// <summary>The instruments the strategy may trade: every one but those used only as data.</summary>
|
||||||
|
public IEnumerable<BacktestInstrument> Tradable => Instruments.Where(i => !DataOnly.Contains(i.Symbol));
|
||||||
|
|
||||||
|
public IReadOnlySet<string> DataOnly { get; }
|
||||||
|
|
||||||
public string Currency { get; }
|
public string Currency { get; }
|
||||||
|
|
||||||
public IReadOnlyList<DateOnly> Sessions { get; }
|
public IReadOnlyList<DateOnly> Sessions { get; }
|
||||||
|
|
||||||
public bool IsCrypto => Instruments.Count > 0 && Instruments.All(i => i.Spec.AssetClass == AssetClasses.Crypto);
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public IReadOnlyList<DateOnly> Calendar { get; }
|
||||||
|
|
||||||
|
/// <summary>The next session after <paramref name="day"/>: every day for crypto, the calendar for stocks.</summary>
|
||||||
|
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);
|
||||||
|
|
||||||
/// <summary>Sessions in a year, to annualise: crypto trades every day, stocks about 252 days.</summary>
|
/// <summary>Sessions in a year, to annualise: crypto trades every day, stocks about 252 days.</summary>
|
||||||
public int PeriodsPerYear => IsCrypto ? 365 : 252;
|
public int PeriodsPerYear => IsCrypto ? 365 : 252;
|
||||||
@@ -130,13 +172,15 @@ public sealed class BacktestDataset
|
|||||||
public BacktestInstrument? this[string symbol] => _bySymbol.GetValueOrDefault(symbol);
|
public BacktestInstrument? this[string symbol] => _bySymbol.GetValueOrDefault(symbol);
|
||||||
|
|
||||||
/// <summary>The same data cut after <paramref name="day"/>: what was known on that day (SPEC 12.2, step 2).</summary>
|
/// <summary>The same data cut after <paramref name="day"/>: what was known on that day (SPEC 12.2, step 2).</summary>
|
||||||
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);
|
||||||
|
|
||||||
/// <summary>The same data between two days, both included.</summary>
|
/// <summary>The same data between two days, both included.</summary>
|
||||||
public BacktestDataset Between(DateOnly from, DateOnly to) => new(
|
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))
|
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),
|
.Where(i => i.Bars.Count > 0),
|
||||||
Currency);
|
Currency,
|
||||||
|
Calendar.Where(d => d >= from),
|
||||||
|
DataOnly);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// A SHA-256 of every bar, action and rule used: two reports with the same fingerprint and the same plan were
|
/// 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();
|
var text = new StringBuilder();
|
||||||
text.Append(Currency).Append('\n');
|
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)
|
foreach (var i in Instruments)
|
||||||
{
|
{
|
||||||
var s = i.Spec;
|
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)
|
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");
|
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");
|
||||||
|
|||||||
@@ -22,6 +22,12 @@ public sealed record BacktestOptions
|
|||||||
|
|
||||||
/// <summary>The risk engine of SPEC 9. Until Phase 5 it lets everything through.</summary>
|
/// <summary>The risk engine of SPEC 9. Until Phase 5 it lets everything through.</summary>
|
||||||
public IIntentStage Risk { get; init; } = PassThroughStage.Risk;
|
public IIntentStage Risk { get; init; } = PassThroughStage.Risk;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public decimal? ReferenceShare { get; init; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>A book to start from: a state recorded live, for the one-step comparison of SPEC 12.3.</summary>
|
/// <summary>A book to start from: a state recorded live, for the one-step comparison of SPEC 12.3.</summary>
|
||||||
@@ -93,6 +99,12 @@ public static class BacktestReasons
|
|||||||
public const string UnknownSymbol = "unknown_symbol";
|
public const string UnknownSymbol = "unknown_symbol";
|
||||||
public const string NoShortSelling = "no_short_selling";
|
public const string NoShortSelling = "no_short_selling";
|
||||||
public const string Dividend = "dividend";
|
public const string Dividend = "dividend";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Prefix of the notes that count the codes of the correctives and of the risk engine on the intents of each close
|
||||||
|
/// (<c>adjusted:trade_risk_limit</c>): how often a rule changed what the strategy asked for.
|
||||||
|
/// </summary>
|
||||||
|
public const string AdjustedPrefix = "adjusted:";
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -105,7 +117,7 @@ public static class BacktestReasons
|
|||||||
public static class BacktestEngine
|
public static class BacktestEngine
|
||||||
{
|
{
|
||||||
/// <summary>Changes when the engine computes differently: plans record it, so a report says which engine made it.</summary>
|
/// <summary>Changes when the engine computes differently: plans record it, so a report says which engine made it.</summary>
|
||||||
public const string Version = "1";
|
public const string Version = "2";
|
||||||
|
|
||||||
public static BacktestRun Run(IStrategy strategy, BacktestDataset data, BacktestOptions? options = null, PortfolioState? start = null)
|
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; }
|
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
|
private sealed class Simulation
|
||||||
{
|
{
|
||||||
@@ -216,6 +231,7 @@ public static class BacktestEngine
|
|||||||
private readonly Dictionary<string, decimal> _lastClose = new(StringComparer.Ordinal);
|
private readonly Dictionary<string, decimal> _lastClose = new(StringComparer.Ordinal);
|
||||||
private readonly Dictionary<string, DateOnly> _actionsDoneThrough = new(StringComparer.Ordinal);
|
private readonly Dictionary<string, DateOnly> _actionsDoneThrough = new(StringComparer.Ordinal);
|
||||||
private readonly List<EquityPoint> _equity = [];
|
private readonly List<EquityPoint> _equity = [];
|
||||||
|
private readonly List<EquityMark> _history = [];
|
||||||
private readonly List<BacktestFill> _fills = [];
|
private readonly List<BacktestFill> _fills = [];
|
||||||
private readonly List<BacktestTrade> _trades = [];
|
private readonly List<BacktestTrade> _trades = [];
|
||||||
private readonly List<DecisionRecord> _decisions = [];
|
private readonly List<DecisionRecord> _decisions = [];
|
||||||
@@ -358,19 +374,44 @@ public static class BacktestEngine
|
|||||||
MarkOn(day);
|
MarkOn(day);
|
||||||
var invested = Invested();
|
var invested = Invested();
|
||||||
_equity.Add(new EquityPoint(day, _cash + invested, _cash, invested));
|
_equity.Add(new EquityPoint(day, _cash + invested, _cash, invested));
|
||||||
|
_history.Add(new EquityMark(day, _cash + invested, invested));
|
||||||
var record = Decide(day, at);
|
var record = Decide(day, at);
|
||||||
_decisions.Add(record);
|
_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)
|
public DecisionRecord Decide(DateOnly day, DateTimeOffset at)
|
||||||
{
|
{
|
||||||
var available = _data.Instruments.Where(i => i.CountThrough(day) > 0).Select(i => i.Symbol).ToList();
|
var available = _data.Tradable.Where(i => i.CountThrough(day) > 0).Select(i => i.Symbol).ToList();
|
||||||
var universe = _strategy.Universe(new UniverseContext(day, available));
|
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 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 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),
|
var context = new StrategyContext(day, at, universe, new PortfolioView(_cash, equity, holdings), Bars, s => _data[s]?.Spec)
|
||||||
s => _data[s]?.SeriesThrough(day) ?? BarSeries.Empty, 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 proposed = _strategy.Decide(context);
|
||||||
var final = proposed;
|
var final = proposed;
|
||||||
foreach (var stage in _options.Correctives)
|
foreach (var stage in _options.Correctives)
|
||||||
@@ -438,7 +479,7 @@ public static class BacktestEngine
|
|||||||
var difference = target - current;
|
var difference = target - current;
|
||||||
if (difference > 0m)
|
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)
|
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.AveragePrice = DbValues.Money(((p.Quantity * p.AveragePrice) + fill.Gross) / (p.Quantity + fill.Quantity));
|
||||||
p.Quantity += fill.Quantity;
|
p.Quantity += fill.Quantity;
|
||||||
p.Stop = order.Stop ?? p.Stop;
|
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.Bought += fill.Gross;
|
||||||
p.Trade.CashFlow += fill.CashDelta;
|
p.Trade.CashFlow += fill.CashDelta;
|
||||||
p.Trade.Fees += fill.FeeValue;
|
p.Trade.Fees += fill.FeeValue;
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ public static class TrialRequestErrors
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public sealed partial class Laboratory : IDisposable
|
public sealed partial class Laboratory : IDisposable
|
||||||
{
|
{
|
||||||
public const int MaxSymbols = 20;
|
public const int MaxSymbols = 60;
|
||||||
|
|
||||||
public const int MaxVariants = 200;
|
public const int MaxVariants = 200;
|
||||||
|
|
||||||
@@ -143,7 +143,10 @@ public sealed partial class Laboratory : IDisposable
|
|||||||
TrialValidation.Default,
|
TrialValidation.Default,
|
||||||
TrialThresholds.Default,
|
TrialThresholds.Default,
|
||||||
BacktestEngine.Version,
|
BacktestEngine.Version,
|
||||||
now);
|
now)
|
||||||
|
{
|
||||||
|
ReferenceShare = StrategyPipeline.DefaultShare(family.Id),
|
||||||
|
};
|
||||||
var variants = ParameterGrid.Of(family, plan.Grid).Count;
|
var variants = ParameterGrid.Of(family, plan.Grid).Count;
|
||||||
if (variants == 0)
|
if (variants == 0)
|
||||||
{
|
{
|
||||||
@@ -261,29 +264,45 @@ public sealed partial class Laboratory : IDisposable
|
|||||||
{
|
{
|
||||||
var instrument = await catalog.FindAsync(data.Venue, symbol, cancellationToken).ConfigureAwait(false)
|
var instrument = await catalog.FindAsync(data.Venue, symbol, cancellationToken).ConfigureAwait(false)
|
||||||
?? throw new InvalidOperationException($"Strumento sconosciuto: {symbol} su {data.Venue}.");
|
?? 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);
|
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
|
else
|
||||||
{
|
{
|
||||||
var store = new ResearchStore(researchRoot);
|
return await LoadResearchAsync(researchRoot, data, cancellationToken).ConfigureAwait(false);
|
||||||
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 List<DailyBar>();
|
|
||||||
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"));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var empty = instruments.FirstOrDefault(i => i.Bars.Count == 0);
|
return Checked(instruments, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The bars of a trial on the research history: no database needed (the protocol runs from the command line).</summary>
|
||||||
|
public static async Task<BacktestDataset> LoadResearchAsync(string researchRoot, TrialData data, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(data);
|
||||||
|
var instruments = new List<BacktestInstrument>();
|
||||||
|
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<DailyBar>();
|
||||||
|
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<BacktestInstrument> 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)
|
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}.");
|
throw new InvalidOperationException($"Nessuna barra giornaliera per {empty.Symbol} tra il {data.From:dd/MM/yyyy} e il {data.To:dd/MM/yyyy}.");
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ public static class LookAheadCheck
|
|||||||
/// <summary>Intents as text, with stops to nine significant digits: adjusted prices may differ in the last bit.</summary>
|
/// <summary>Intents as text, with stops to nine significant digits: adjusted prices may differ in the last bit.</summary>
|
||||||
private static string Describe(IReadOnlyList<Intent> intents) => string.Join(" | ", intents.Select(i => string.Create(
|
private static string Describe(IReadOnlyList<Intent> intents) => string.Join(" | ", intents.Select(i => string.Create(
|
||||||
CultureInfo.InvariantCulture,
|
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}")));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>How the live intent and the backtest intent for one instrument compare (SPEC 12.3).</summary>
|
/// <summary>How the live intent and the backtest intent for one instrument compare (SPEC 12.3).</summary>
|
||||||
|
|||||||
@@ -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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public static class EuroHistory
|
||||||
|
{
|
||||||
|
public const string Venue = "binance_eur";
|
||||||
|
|
||||||
|
/// <summary>A rate older than this is not used: the ECB never skips more than a long holiday weekend.</summary>
|
||||||
|
public static readonly int MaxRateAgeDays = 7;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public static readonly int MaxGapDays = 7;
|
||||||
|
|
||||||
|
/// <summary><c>BTCUSDT</c> becomes <c>BTCEUR</c>.</summary>
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Divides prices and traded value by the last EUR/USD rate fixed before the bar opens: the rate of the day before,
|
||||||
|
/// or of the last day before that with a rate. The rate of day d is fixed at 16:00 CET of d, after the bar of d
|
||||||
|
/// opens at 00:00 UTC, so using it for that bar's open (where the backtest fills) would read the future. A bar is
|
||||||
|
/// dropped when no rate of the last <see cref="MaxRateAgeDays"/> days exists. The series stops at the first hole
|
||||||
|
/// longer than <see cref="MaxGapDays"/> days.
|
||||||
|
/// </summary>
|
||||||
|
public static IReadOnlyList<ResearchBar> Convert(IEnumerable<ResearchBar> bars, IReadOnlyList<FxRate> eurUsd)
|
||||||
|
{
|
||||||
|
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<ResearchBar>();
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Converts every daily USDT series of the Binance archives in the store. Returns the symbols written.</summary>
|
||||||
|
public static async Task<IReadOnlyList<string>> ConvertAllAsync(ResearchStore store, IReadOnlyList<FxRate> eurUsd, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(store);
|
||||||
|
var written = new List<string>();
|
||||||
|
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<ResearchBar>();
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A trial of the protocol: which universe, its report and the daily returns of the chosen variant.</summary>
|
||||||
|
public sealed record ProtocolRun(string Name, string Description, TrialPlan Plan, BacktestReport Report, IReadOnlyList<double> DailyReturns, decimal ExpectedSlippageBp);
|
||||||
|
|
||||||
|
/// <summary>What the protocol of a strategy concluded: the outcome file and the trials behind it.</summary>
|
||||||
|
public sealed record ProtocolOutcome(Qualification Qualification, IReadOnlyList<ProtocolRun> Runs);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The anti-illusion protocol of SPEC 12.2 for <c>crypto_trend</c>, 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.
|
||||||
|
/// </summary>
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>Two years of Binance history before this day are enough for the longest period (360) and the 400 days of age.</summary>
|
||||||
|
public static readonly DateOnly From = new(2019, 1, 1);
|
||||||
|
|
||||||
|
public static readonly IReadOnlyList<string> Narrow = ["BTCEUR", "ETHEUR", "SOLEUR"];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public static readonly IReadOnlyList<string> Archives =
|
||||||
|
[
|
||||||
|
"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",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>Length of the expected path of the outcome: one year of daily closes.</summary>
|
||||||
|
public const int PathDays = 365;
|
||||||
|
|
||||||
|
public static async Task<ProtocolOutcome> RunAsync(string researchRoot, DateOnly to, DateTimeOffset now, Action<string>? progress, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var store = new ResearchStore(researchRoot);
|
||||||
|
var broad = new List<string>();
|
||||||
|
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<ProtocolRun> runs = [first, second];
|
||||||
|
return new ProtocolOutcome(QualificationOf(runs), runs);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The outcome file: passed only when every trial passed; measures from the broad universe, the one traded live.</summary>
|
||||||
|
public static Qualification QualificationOf(IReadOnlyList<ProtocolRun> runs)
|
||||||
|
{
|
||||||
|
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))],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A failed check in plain Italian, e.g. "calo massimo 38,2%, oltre il 25%".</summary>
|
||||||
|
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 Task<ProtocolRun> RunOneAsync(IStrategyFamily family, string name, string description, IReadOnlyList<string> symbols, DateOnly to,
|
||||||
|
DateTimeOffset now, string researchRoot, PriorTrials prior, Action<string>? 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<bool> 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public static class PathBootstrap
|
||||||
|
{
|
||||||
|
public const int Paths = 2000;
|
||||||
|
|
||||||
|
public const int Block = 20;
|
||||||
|
|
||||||
|
public const int Seed = 20_260_101;
|
||||||
|
|
||||||
|
public static IReadOnlyList<double> Percentile(IReadOnlyList<double> 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The outcome files of <c>docs/backtests/</c>, 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).
|
||||||
|
/// </summary>
|
||||||
|
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.Deserialize<Qualification>(stream, Qualification.Json);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly JsonSerializerOptions Indented = new(Qualification.Json) { WriteIndented = true };
|
||||||
|
|
||||||
|
public static string ToJson(Qualification qualification) => JsonSerializer.Serialize(qualification, Indented) + "\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public static class EquityProtocol
|
||||||
|
{
|
||||||
|
public static readonly IReadOnlyList<string> Explanation =
|
||||||
|
[
|
||||||
|
"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",
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Text;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Backtest;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The report of <c>docs/backtests/</c> 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.
|
||||||
|
/// </summary>
|
||||||
|
public static class ProtocolReport
|
||||||
|
{
|
||||||
|
private static readonly CultureInfo It = CultureInfo.GetCultureInfo("it-IT");
|
||||||
|
|
||||||
|
public static string Markdown(ProtocolOutcome outcome, string title, IReadOnlyList<string> 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();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The report of a strategy whose backtest cannot run yet, with what it waits for.</summary>
|
||||||
|
public static string Waiting(string strategy, string name, Qualification qualification, IReadOnlyList<string> lines)
|
||||||
|
{
|
||||||
|
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<string, int> 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);
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
|
using System.Globalization;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Anubis.Data;
|
using Anubis.Data;
|
||||||
using Anubis.Strategies;
|
using Anubis.Strategies;
|
||||||
@@ -105,9 +106,10 @@ public static class TrialRunner
|
|||||||
ArgumentNullException.ThrowIfNull(data);
|
ArgumentNullException.ThrowIfNull(data);
|
||||||
ArgumentNullException.ThrowIfNull(prior);
|
ArgumentNullException.ThrowIfNull(prior);
|
||||||
var watch = Stopwatch.StartNew();
|
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);
|
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.");
|
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];
|
var runs = new BacktestRun[variants.Count];
|
||||||
for (var i = 0; i < variants.Count; i++)
|
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));
|
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);
|
var benchmark = BacktestMetrics.Of(benchmarkRun, data.PeriodsPerYear);
|
||||||
|
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
@@ -201,7 +205,7 @@ public static class TrialRunner
|
|||||||
data.Fingerprint(),
|
data.Fingerprint(),
|
||||||
data.Currency,
|
data.Currency,
|
||||||
data.PeriodsPerYear,
|
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,
|
[.. 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))],
|
i.Bars.Count > 0 ? i.Bars[^1].Day : null, i.Bars.Count, i.Actions.Count, i.Source))],
|
||||||
chosen.ToString(),
|
chosen.ToString(),
|
||||||
@@ -241,11 +245,26 @@ public static class TrialRunner
|
|||||||
var result = new List<string>
|
var result = new List<string>
|
||||||
{
|
{
|
||||||
"I correttivi senza una storia ricostruibile (notizie, calendario economico, trimestrali, modello) non ricevono dati e non intervengono.",
|
"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.",
|
"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.",
|
"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.");
|
result.Add("Prezzi dello storico Binance in USDT: passo di prezzo e quantità minima sono stime, i costi sono quelli di OKX.");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,247 @@
|
|||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Risk;
|
||||||
|
using Anubis.Strategies;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Backtest;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class BacktestRisk(RiskLimits? limits = null) : IIntentStage
|
||||||
|
{
|
||||||
|
/// <summary>When the user is assumed to confirm the restart after the switch tripped.</summary>
|
||||||
|
public static readonly TimeSpan AssumedRestart = TimeSpan.FromDays(7);
|
||||||
|
|
||||||
|
private readonly RiskLimits _limits = limits ?? RiskLimits.Default;
|
||||||
|
private readonly ConditionalWeakTable<IReadOnlyList<EquityMark>, Walker> _walkers = [];
|
||||||
|
|
||||||
|
public string Name => "risk";
|
||||||
|
|
||||||
|
public RiskLimits Limits => _limits;
|
||||||
|
|
||||||
|
/// <summary>Each close as a moment: noon UTC, inside its own Italian day.</summary>
|
||||||
|
public static DateTimeOffset At(DateOnly day) => new(day.ToDateTime(new TimeOnly(12, 0)), TimeSpan.Zero);
|
||||||
|
|
||||||
|
public IReadOnlyList<Intent> Apply(StrategyContext context, IReadOnlyList<Intent> 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<Intent>(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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The loss monitor walked along one run's closes, one step for each new close.</summary>
|
||||||
|
private sealed class Walker(RiskLimits limits)
|
||||||
|
{
|
||||||
|
private readonly Lock _lock = new();
|
||||||
|
private readonly List<IndexPoint> _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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
IReadOnlyList<IIntentStage> correctives = [];
|
||||||
|
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) };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,8 +17,19 @@ public static class TrialSources
|
|||||||
public const string Research = "research";
|
public const string Research = "research";
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The data a trial reads: one venue, a few instruments, a period (both days included).</summary>
|
/// <summary>
|
||||||
public sealed record TrialData(string Source, string Venue, IReadOnlyList<string> Symbols, DateOnly From, DateOnly To);
|
/// The data a trial reads: one venue, a few instruments, a period (both days included). The bars of the
|
||||||
|
/// <see cref="WarmupDays"/> before <see cref="From"/> 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 <see cref="From"/>.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record TrialData(string Source, string Venue, IReadOnlyList<string> Symbols, DateOnly From, DateOnly To)
|
||||||
|
{
|
||||||
|
/// <summary>Calendar days of history before the start: a year of 252 sessions, a 360-day lookback, 400 days of listing.</summary>
|
||||||
|
public const int WarmupDays = 450;
|
||||||
|
|
||||||
|
/// <summary>The first day read from the history.</summary>
|
||||||
|
public DateOnly HistoryStart() => From.AddDays(-WarmupDays);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The thresholds of SPEC 12.2, fixed in the plan before the trial runs: changing them after seeing the results needs
|
/// 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,
|
string Engine,
|
||||||
DateTimeOffset WrittenAt)
|
DateTimeOffset WrittenAt)
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public decimal? ReferenceShare { get; init; }
|
||||||
|
|
||||||
public static readonly JsonSerializerOptions Json = new()
|
public static readonly JsonSerializerOptions Json = new()
|
||||||
{
|
{
|
||||||
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
|
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
|
||||||
|
|||||||
@@ -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",
|
public static readonly SettingDefinition CentralBankMeetings = new("calendar.central_banks", "Riunioni di Fed e BCE",
|
||||||
Data.CentralBanks.DefaultList, Check: Data.CentralBanks.Check);
|
Data.CentralBanks.DefaultList, Check: Data.CentralBanks.Check);
|
||||||
|
|
||||||
public static readonly IReadOnlyList<SettingDefinition> All = [Theme, Currency, BotState, CentralBankMeetings];
|
public static readonly IReadOnlyList<SettingDefinition> All =
|
||||||
|
[Theme, Currency, BotState, CentralBankMeetings, .. Risk.RiskSettings.All, Risk.Scenarios.Setting];
|
||||||
|
|
||||||
private readonly IReadOnlyDictionary<string, StartupOverride> _overrides = overrides ?? new Dictionary<string, StartupOverride>();
|
private readonly IReadOnlyDictionary<string, StartupOverride> _overrides = overrides ?? new Dictionary<string, StartupOverride>();
|
||||||
|
|
||||||
|
|||||||
@@ -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};
|
||||||
@@ -120,10 +120,25 @@ public static class DemoMode
|
|||||||
["Mean reversion"] = ("equity_meanrev", alpaca, 1740.15m, 1236.71m, 0.25m),
|
["Mean reversion"] = ("equity_meanrev", alpaca, 1740.15m, 1236.71m, 0.25m),
|
||||||
};
|
};
|
||||||
var currencyOf = new Dictionary<Guid, string> { [okx] = "EUR", [alpaca] = "USD" };
|
var currencyOf = new Dictionary<Guid, string> { [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)
|
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)",
|
var example = new Trading.Qualification
|
||||||
cancellationToken, ("id", ids.Next()), ("n", name), ("a", account), ("c", capital), ("sh", share), ("st", new DbJson("{\"day\":58,\"of\":60}")), ("t", now))
|
{
|
||||||
|
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);
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -177,20 +192,22 @@ public static class DemoMode
|
|||||||
[
|
[
|
||||||
("account", okx, null, 4000m, 231.60m),
|
("account", okx, null, 4000m, 231.60m),
|
||||||
("account", alpaca, null, 6000m, 180.86m),
|
("account", alpaca, null, 6000m, 180.86m),
|
||||||
("strategy", null, "crypto_trend", 4000m, 231.60m),
|
("strategy", okx, "crypto_trend", 4000m, 231.60m),
|
||||||
("strategy", null, "equity_momentum", 4500m, 169.50m),
|
("strategy", alpaca, "equity_momentum", 4500m, 169.50m),
|
||||||
("strategy", null, "equity_meanrev", 1500m, 11.36m),
|
("strategy", alpaca, "equity_meanrev", 1500m, 11.36m),
|
||||||
];
|
];
|
||||||
foreach (var (day, equity, benchmark, drawdown) in daily)
|
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))));
|
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)",
|
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), ("t", now)).ConfigureAwait(false);
|
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)
|
foreach (var (scope, account, strategy, start, result) in series)
|
||||||
{
|
{
|
||||||
var value = Math.Round(start + (equity - 10000m) * result / total, 2, MidpointRounding.AwayFromZero);
|
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)",
|
// Without deposits along the way the index is the value over the start.
|
||||||
cancellationToken, ("id", ids.Next()), ("at", at), ("sc", scope), ("a", account), ("st", strategy), ("e", value), ("t", now)).ConfigureAwait(false);
|
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)",
|
"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),
|
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);
|
("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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,151 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Anubis.Core;
|
||||||
|
|
||||||
|
namespace Anubis.Risk;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record RiskLimits
|
||||||
|
{
|
||||||
|
/// <summary>Loss in a day (Italian midnight to now): no new entries for 24 hours.</summary>
|
||||||
|
public decimal DailyLoss { get; init; } = 0.02m;
|
||||||
|
|
||||||
|
/// <summary>Loss over the last seven days: risk halved for seven days.</summary>
|
||||||
|
public decimal WeeklyLoss { get; init; } = 0.05m;
|
||||||
|
|
||||||
|
/// <summary>Fall from the high at which the risk is halved.</summary>
|
||||||
|
public decimal DrawdownHalf { get; init; } = 0.10m;
|
||||||
|
|
||||||
|
/// <summary>Fall from the high at which the emergency switch trips and the bot waits for the user.</summary>
|
||||||
|
public decimal DrawdownStop { get; init; } = 0.15m;
|
||||||
|
|
||||||
|
/// <summary>Capital in positions over the world's equity: no other purchase beyond it.</summary>
|
||||||
|
public decimal MaxInvested { get; init; } = 1m;
|
||||||
|
|
||||||
|
/// <summary>One position over the reference equity: brought back to the threshold at the first chance.</summary>
|
||||||
|
public decimal MaxPosition { get; init; } = 0.20m;
|
||||||
|
|
||||||
|
/// <summary>Crypto over the reference equity: no new crypto purchases beyond it.</summary>
|
||||||
|
public decimal MaxCrypto { get; init; } = 0.40m;
|
||||||
|
|
||||||
|
/// <summary>Loss if the stop of a whole position triggered, over the reference equity: the purchase is shrunk.</summary>
|
||||||
|
public decimal MaxTradeRisk { get; init; } = 0.01m;
|
||||||
|
|
||||||
|
/// <summary>Purchases and sales really sent to one account in a minute: beyond, the bot stops and warns.</summary>
|
||||||
|
public int OrdersPerMinute { get; init; } = 10;
|
||||||
|
|
||||||
|
/// <summary>Age of the last price: no new entry on the instrument beyond it.</summary>
|
||||||
|
public TimeSpan MaxPriceAge { get; init; } = TimeSpan.FromSeconds(60);
|
||||||
|
|
||||||
|
/// <summary>Distance of a purchase's limit from the last valid price: refused beyond it.</summary>
|
||||||
|
public decimal MaxPriceGap { get; init; } = 0.01m;
|
||||||
|
|
||||||
|
/// <summary>Gap between the bot's clock and the broker's: no new entries beyond it.</summary>
|
||||||
|
public TimeSpan MaxClockSkew { get; init; } = TimeSpan.FromSeconds(2);
|
||||||
|
|
||||||
|
/// <summary>Share of a threshold at which a warning starts, without any block (SPEC 9.2).</summary>
|
||||||
|
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();
|
||||||
|
|
||||||
|
/// <summary>True when <paramref name="next"/> allows more risk than this on at least one limit.</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
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));
|
||||||
|
|
||||||
|
/// <summary>Day-trade protection (SPEC 9.2, <c>pdt_guard</c>): off by default.</summary>
|
||||||
|
public static readonly SettingDefinition PdtGuard = new("risk.pdt_guard", "Protezione day trade", "off", ["off", "on"]);
|
||||||
|
|
||||||
|
public static readonly IReadOnlyList<SettingDefinition> Limits =
|
||||||
|
[DailyLoss, WeeklyLoss, DrawdownHalf, DrawdownStop, MaxInvested, MaxPosition, MaxCrypto, MaxTradeRisk, OrdersPerMinute, MaxPriceAge, MaxPriceGap, MaxClockSkew];
|
||||||
|
|
||||||
|
public static readonly IReadOnlyList<SettingDefinition> All = [.. Limits, PdtGuard];
|
||||||
|
|
||||||
|
/// <summary>The limits from settings: <paramref name="value"/> reads a key and returns its text.</summary>
|
||||||
|
public static RiskLimits From(Func<string, string> 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<RiskLimits> LoadAsync(SettingsStore settings, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(settings);
|
||||||
|
var values = new Dictionary<string, string>(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<bool> 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}.";
|
||||||
|
}
|
||||||
@@ -0,0 +1,259 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Anubis.Data;
|
||||||
|
|
||||||
|
namespace Anubis.Risk;
|
||||||
|
|
||||||
|
/// <summary>A point of a world's time-weighted index: deposits and withdrawals never look like gains or losses (SPEC 7.5).</summary>
|
||||||
|
public sealed record IndexPoint(DateTimeOffset At, decimal Index);
|
||||||
|
|
||||||
|
/// <summary>The three measures of SPEC 9.2, as changes: −0.03 is a loss of 3%.</summary>
|
||||||
|
public sealed record RiskMeasures(decimal DayChange, decimal WeekChange, decimal Drawdown)
|
||||||
|
{
|
||||||
|
public static RiskMeasures None { get; } = new(0m, 0m, 0m);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The measures at <paramref name="now"/>: the day starts at Italian midnight, the week is the last seven days, the
|
||||||
|
/// high is the highest point since <paramref name="peakFrom"/> (the start, or the last confirmed restart).
|
||||||
|
/// </summary>
|
||||||
|
public static RiskMeasures From(IReadOnlyList<IndexPoint> 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 };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The index the measures were taken on.</summary>
|
||||||
|
public decimal? Index { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The high the fall is measured from: kept by the engine between readings, so the series can be short.</summary>
|
||||||
|
public decimal? Peak { get; init; }
|
||||||
|
|
||||||
|
public static decimal Change(decimal current, decimal reference) => reference <= 0m ? 0m : (current / reference) - 1m;
|
||||||
|
|
||||||
|
private static int LastAtOrBefore(IReadOnlyList<IndexPoint> series, 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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).
|
||||||
|
/// </summary>
|
||||||
|
public sealed record RiskMonitorState
|
||||||
|
{
|
||||||
|
public DateTimeOffset? DailyBlockUntil { get; init; }
|
||||||
|
|
||||||
|
public DateTimeOffset? WeeklyHalvingUntil { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The high counts points from this moment: the start, or the last confirmed restart after a trip.</summary>
|
||||||
|
public DateTimeOffset? PeakFrom { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The highest index seen since <see cref="PeakFrom"/>.</summary>
|
||||||
|
public decimal? Peak { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The fall from the high reached the stop threshold: entries and sales of the strategies stop until the user confirms.</summary>
|
||||||
|
public bool Tripped { get; init; }
|
||||||
|
|
||||||
|
public DateTimeOffset? TrippedAt { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Measures beyond 80% of their threshold, already warned about; a measure leaves the list when it comes back.</summary>
|
||||||
|
public IReadOnlyList<string> Warned { get; init; } = [];
|
||||||
|
|
||||||
|
public static RiskMonitorState Initial { get; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Something the monitor saw: a limit crossed, a warning at 80% of a threshold.</summary>
|
||||||
|
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, IReadOnlyList<RiskAlert> Alerts);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public static class RiskMonitor
|
||||||
|
{
|
||||||
|
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT");
|
||||||
|
|
||||||
|
/// <summary>Midnight in Italy of the day <paramref name="at"/> falls on, as a UTC moment.</summary>
|
||||||
|
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 List<RiskAlert>();
|
||||||
|
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<string>(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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>No new entries: the 24-hour block after a day's loss, or the switch tripped by the fall from the high.</summary>
|
||||||
|
public static bool EntriesBlocked(RiskMonitorState state, DateTimeOffset now)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(state);
|
||||||
|
return state.Tripped || state.DailyBlockUntil > now;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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).
|
||||||
|
/// </summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
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) + "%";
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
namespace Anubis.Risk;
|
||||||
|
|
||||||
|
/// <summary>Reason codes of the risk engine: every reduction and every refusal leaves one (SPEC 5.2).</summary>
|
||||||
|
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";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A purchase as the risk engine sees it, every amount in one currency. <see cref="Reference"/> is the reference
|
||||||
|
/// equity of SPEC 9.2 (a quarter of it for a strategy in reduced real); <see cref="WorldEquity"/> and
|
||||||
|
/// <see cref="WorldInvested"/> are those of the world the order belongs to.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record PurchaseRequest
|
||||||
|
{
|
||||||
|
public required decimal Price { get; init; }
|
||||||
|
|
||||||
|
public required decimal Held { get; init; }
|
||||||
|
|
||||||
|
public required decimal Wanted { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The stop of the whole position after the purchase; null means none, and the risk is the whole position.</summary>
|
||||||
|
public decimal? Stop { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Product of the reductions in force (correctives and loss limits): one or less.</summary>
|
||||||
|
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; }
|
||||||
|
|
||||||
|
/// <summary>Crypto already held by the bot, on every account of the world.</summary>
|
||||||
|
public decimal CryptoValue { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record PurchaseSize(decimal Quantity, IReadOnlyList<string> Reasons)
|
||||||
|
{
|
||||||
|
public bool Reduced => Reasons.Count > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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).
|
||||||
|
/// </summary>
|
||||||
|
public static class RiskRules
|
||||||
|
{
|
||||||
|
public static PurchaseSize SizePurchase(PurchaseRequest r, RiskLimits limits)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(r);
|
||||||
|
ArgumentNullException.ThrowIfNull(limits);
|
||||||
|
var reasons = new List<string>();
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What to sell of a position heavier than the threshold, to bring it back to it; zero when it is within.</summary>
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The technical checks of SPEC 9.2: they stop entries only, never stops and sales (trap 25).</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Anubis.Core;
|
||||||
|
|
||||||
|
namespace Anubis.Risk;
|
||||||
|
|
||||||
|
/// <summary>A "what if it happened tomorrow" of SPEC 9.5: price changes of crypto and US stocks, and of the dollar on the euro.</summary>
|
||||||
|
public sealed record Scenario(string Label, decimal Crypto, decimal Stocks, decimal Dollar);
|
||||||
|
|
||||||
|
/// <summary>A position of the bot valued in euro, with the value it would have at its stop.</summary>
|
||||||
|
public sealed record ScenarioPosition(bool IsCrypto, decimal ValueEur, decimal? ValueAtStopEur);
|
||||||
|
|
||||||
|
public sealed record ScenarioResult(Scenario Scenario, decimal WithoutStops, decimal WithoutStopsShare, decimal? WithStops, bool SameWithStops);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public static class Scenarios
|
||||||
|
{
|
||||||
|
public static readonly IReadOnlyList<Scenario> Default =
|
||||||
|
[
|
||||||
|
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),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>The scenarios as a setting, one per line: <c>label; crypto %; stocks %; dollar %</c>.</summary>
|
||||||
|
public static readonly SettingDefinition Setting = new("risk.scenarios", "Scenari \"Se succedesse domani\"", Write(Default), Check: Check);
|
||||||
|
|
||||||
|
public static IReadOnlyList<ScenarioResult> Compute(IReadOnlyList<Scenario> scenarios, IReadOnlyList<ScenarioPosition> positions, decimal dollarAccountEur, decimal equityEur)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(scenarios);
|
||||||
|
ArgumentNullException.ThrowIfNull(positions);
|
||||||
|
var result = new List<ScenarioResult>();
|
||||||
|
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<Scenario> Parse(string text)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(text);
|
||||||
|
var list = new List<Scenario>();
|
||||||
|
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<Scenario> 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);
|
||||||
|
}
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
using Anubis.Data;
|
||||||
|
|
||||||
|
namespace Anubis.Strategies;
|
||||||
|
|
||||||
|
/// <summary>Reason codes of the correctives (SPEC 8.5): each intervention leaves its own.</summary>
|
||||||
|
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";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Weights of the strategy's book at the moment of the decision, as the correctives and the risk engine read them.</summary>
|
||||||
|
public static class BookWeights
|
||||||
|
{
|
||||||
|
/// <summary>The last price of an instrument: today's close, or the average price when there are no bars.</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>Volatility measured on 30 daily returns, compared with its own values of the last two years.</summary>
|
||||||
|
public int VolatilityDays { get; init; } = 30;
|
||||||
|
|
||||||
|
public int PercentileDays { get; init; } = 730;
|
||||||
|
|
||||||
|
public double Percentile { get; init; } = 0.9;
|
||||||
|
|
||||||
|
/// <summary>Fewer values than this and the percentile is not used: a year is the least to call something high.</summary>
|
||||||
|
public int MinPercentileDays { get; init; } = 365;
|
||||||
|
|
||||||
|
public decimal Multiplier { get; init; } = 0.5m;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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 <c>crypto_trend</c> are halved.
|
||||||
|
/// </summary>
|
||||||
|
public static class CryptoRegime
|
||||||
|
{
|
||||||
|
/// <summary>Null when the regime is calm, otherwise the reason code.</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Standard deviation of the last <paramref name="window"/> daily log returns, for each of the last <paramref name="days"/> days.</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The crypto regime as a step of the decision: it reduces the entries of the strategy it is given to.</summary>
|
||||||
|
public sealed class CryptoRegimeStage(string bitcoin, CryptoRegimeSettings? settings = null) : IIntentStage
|
||||||
|
{
|
||||||
|
private readonly CryptoRegimeSettings _settings = settings ?? new CryptoRegimeSettings();
|
||||||
|
|
||||||
|
public string Name => "crypto_regime";
|
||||||
|
|
||||||
|
public IReadOnlyList<Intent> Apply(StrategyContext context, IReadOnlyList<Intent> 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))];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
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);
|
||||||
|
|
||||||
|
/// <summary>The window of an event that blocks entries, or null for one that does not (low impact, another currency, no time).</summary>
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The end of the block <paramref name="at"/> falls in, following windows that overlap; null when there is none.</summary>
|
||||||
|
public static DateTimeOffset? BlockedUntil(DateTimeOffset at, IEnumerable<CalendarEvent> 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>When a blocked entry is tried again; null means it is dropped, with its reason code.</summary>
|
||||||
|
public static DateTimeOffset? RetryAt(DateTimeOffset at, IEnumerable<CalendarEvent> events, DateTimeOffset deadline) =>
|
||||||
|
BlockedUntil(at, events) is { } end ? end <= deadline ? end : null : at;
|
||||||
|
|
||||||
|
/// <summary>The deadline of a crypto entry (SPEC 5.6): 12:00 UTC of the same day.</summary>
|
||||||
|
public static DateTimeOffset CryptoDeadline(DateTimeOffset at) => new(at.UtcDateTime.Date.AddHours(12), TimeSpan.Zero);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The calendar block as a step of the decision: during a window no intent may increase a position.</summary>
|
||||||
|
public sealed class CalendarStage(Func<DateTimeOffset, IReadOnlyList<CalendarEvent>> events) : IIntentStage
|
||||||
|
{
|
||||||
|
public string Name => "calendar";
|
||||||
|
|
||||||
|
public IReadOnlyList<Intent> Apply(StrategyContext context, IReadOnlyList<Intent> 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))];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,478 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Anubis.Data;
|
||||||
|
|
||||||
|
namespace Anubis.Strategies;
|
||||||
|
|
||||||
|
/// <summary>The fixed rules of <c>crypto_trend</c> (SPEC 8.1). Only the two family parameters move in a test.</summary>
|
||||||
|
public sealed record CryptoTrendSettings
|
||||||
|
{
|
||||||
|
public IReadOnlyList<int> Periods { get; init; } = [5, 10, 20, 30, 60, 90, 150, 250, 360];
|
||||||
|
|
||||||
|
/// <summary>Volatility each coin is sized to: raw weight = e × this / its volatility.</summary>
|
||||||
|
public double CoinVolatility { get; init; } = 0.15;
|
||||||
|
|
||||||
|
/// <summary>Above this estimated volatility of the whole strategy, every weight shrinks by one factor.</summary>
|
||||||
|
public double StrategyVolatility { get; init; } = 0.20;
|
||||||
|
|
||||||
|
/// <summary>The server stop is never further than this below the last close.</summary>
|
||||||
|
public double MaxStop { get; init; } = 0.15;
|
||||||
|
|
||||||
|
public decimal MajorCap { get; init; } = 0.35m;
|
||||||
|
|
||||||
|
public decimal OtherCap { get; init; } = 0.20m;
|
||||||
|
|
||||||
|
public IReadOnlySet<string> Majors { get; init; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "BTC", "ETH" };
|
||||||
|
|
||||||
|
public int VolatilityWindow { get; init; } = 90;
|
||||||
|
|
||||||
|
/// <summary>A position is resized only when it is this far from its target, relative to the target…</summary>
|
||||||
|
public decimal RebalanceRelative { get; init; } = 0.20m;
|
||||||
|
|
||||||
|
/// <summary>…and this far in share of the strategy's capital.</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <c>crypto_trend</c> (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, <c>e</c>, 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.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class CryptoTrend(CryptoTrendSettings? settings = null) : IStrategy
|
||||||
|
{
|
||||||
|
private readonly CryptoTrendSettings _settings = settings ?? new CryptoTrendSettings();
|
||||||
|
private readonly Dictionary<string, TrendTracker> _trackers = new(StringComparer.Ordinal);
|
||||||
|
private (string Key, IReadOnlyList<string> Members)? _universe;
|
||||||
|
|
||||||
|
public string Id => CryptoTrendFamily.FamilyId;
|
||||||
|
|
||||||
|
public string Version => CryptoTrendFamily.FamilyVersion;
|
||||||
|
|
||||||
|
public CryptoTrendSettings Settings => _settings;
|
||||||
|
|
||||||
|
/// <summary>Once a day on the 00:00 UTC close (SPEC 8.1); orders go right after.</summary>
|
||||||
|
public IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public IReadOnlyList<string> Universe(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<Intent> 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<string>(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<Row>();
|
||||||
|
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<Intent>();
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The state of a coin as of its last bar walked: the nine periods, <c>e</c>, the server stop.</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class TrendTracker
|
||||||
|
{
|
||||||
|
private bool[] _active = [];
|
||||||
|
private double[] _stops = [];
|
||||||
|
private int _walked;
|
||||||
|
private DateOnly? _first;
|
||||||
|
private DateOnly? _last;
|
||||||
|
|
||||||
|
/// <summary>The average of the period states, between 0 and 1.</summary>
|
||||||
|
public double Ensemble { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>The level of the stop on the broker; null when no period is on.</summary>
|
||||||
|
public double? ServerStop { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>The day of the last bar walked.</summary>
|
||||||
|
public DateOnly? LastDay => _last;
|
||||||
|
|
||||||
|
public IReadOnlyList<bool> Active => _active;
|
||||||
|
|
||||||
|
/// <summary>Walks the bars not walked yet. A history that does not continue the one walked starts again.</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The highest of the N closes before bar i.</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The middle between the highest and the lowest of the last N closes, bar i included.</summary>
|
||||||
|
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 IReadOnlyList<ParameterSpec> Parameters =>
|
||||||
|
[
|
||||||
|
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,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Reading the coin or company behind a symbol.</summary>
|
||||||
|
public static class Symbols
|
||||||
|
{
|
||||||
|
private static readonly string[] Quotes = ["USDT", "USDC", "EUR", "USD", "BTC"];
|
||||||
|
|
||||||
|
/// <summary>The base currency of a pair: <c>BTC</c> for <c>BTC-EUR</c> and for <c>BTCUSDT</c>.</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,546 @@
|
|||||||
|
using Anubis.Data;
|
||||||
|
|
||||||
|
namespace Anubis.Strategies;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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).
|
||||||
|
/// </summary>
|
||||||
|
public static class EquityUniverseRanking
|
||||||
|
{
|
||||||
|
public static IReadOnlyList<string> Rank(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)];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Monday of the week of a day: two days are in the same week when their Mondays match.</summary>
|
||||||
|
public static DateOnly WeekOf(DateOnly day) => day.AddDays(-(((int)day.DayOfWeek + 6) % 7));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The fixed rules of <c>equity_momentum</c> (SPEC 8.2).</summary>
|
||||||
|
public sealed record EquityMomentumSettings
|
||||||
|
{
|
||||||
|
public int UniverseSize { get; init; } = EquityUniverse.Size;
|
||||||
|
|
||||||
|
public IReadOnlyList<int> Lookbacks { get; init; } = [63, 126, 252];
|
||||||
|
|
||||||
|
/// <summary>The returns skip the last sessions (short-term reversal).</summary>
|
||||||
|
public int Skip { get; init; } = 5;
|
||||||
|
|
||||||
|
/// <summary>New entries among the first of the ranking…</summary>
|
||||||
|
public int Top { get; init; } = 12;
|
||||||
|
|
||||||
|
/// <summary>…and a stock held leaves when it falls out of these.</summary>
|
||||||
|
public int Keep { get; init; } = 30;
|
||||||
|
|
||||||
|
public int MaxPositions { get; init; } = 12;
|
||||||
|
|
||||||
|
/// <summary>Each stock must close above its own average of these sessions.</summary>
|
||||||
|
public int Trend { get; init; } = 100;
|
||||||
|
|
||||||
|
/// <summary>The market filter: SPY above its average of these sessions.</summary>
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>A position already open is resized only when this far from its target, relative to the target.</summary>
|
||||||
|
public decimal Rebalance { get; init; } = 0.25m;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <c>equity_momentum</c> (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.
|
||||||
|
/// </summary>
|
||||||
|
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 IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
|
||||||
|
|
||||||
|
public IReadOnlyList<string> Universe(UniverseContext context)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(context);
|
||||||
|
return context.Members?.Invoke(Id, context.Day) ?? EquityUniverseRanking.Rank(context, _settings.UniverseSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>True when the next session opens a new week: the close of today is the time of the weekly review.</summary>
|
||||||
|
public static bool IsReview(StrategyContext context)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(context);
|
||||||
|
return context.NextSession is { } next && EquityUniverseRanking.WeekOf(next) != EquityUniverseRanking.WeekOf(context.Day);
|
||||||
|
}
|
||||||
|
|
||||||
|
public IReadOnlyList<Intent> Decide(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<string, decimal>(StringComparer.Ordinal);
|
||||||
|
foreach (var symbol in held)
|
||||||
|
{
|
||||||
|
if (TrailingStop(context, symbol) is { } stop)
|
||||||
|
{
|
||||||
|
stops[symbol] = stop;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var intents = new SortedDictionary<string, Intent>(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<string>();
|
||||||
|
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<string>();
|
||||||
|
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];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
private Dictionary<string, decimal> Weights(StrategyContext context, IReadOnlyList<string> members)
|
||||||
|
{
|
||||||
|
var inverse = new Dictionary<string, double>(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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>3 ATR(20) below the highest close since the entry; it can only rise.</summary>
|
||||||
|
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 IReadOnlyList<ParameterSpec> Parameters =>
|
||||||
|
[
|
||||||
|
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"],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The fixed rules of <c>equity_meanrev</c> (SPEC 8.3).</summary>
|
||||||
|
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;
|
||||||
|
|
||||||
|
/// <summary>The entry session is the first: the time exit comes at the close of the fifth.</summary>
|
||||||
|
public int MaxSessions { get; init; } = 5;
|
||||||
|
|
||||||
|
public int AtrLength { get; init; } = 14;
|
||||||
|
|
||||||
|
public double AtrMultiple { get; init; } = 2.5;
|
||||||
|
|
||||||
|
/// <summary>Risk of one operation, as a share of the reference equity of SPEC 9.2.</summary>
|
||||||
|
public decimal RiskPerTrade { get; init; } = 0.004m;
|
||||||
|
|
||||||
|
public decimal Cap { get; init; } = 0.30m;
|
||||||
|
|
||||||
|
/// <summary>The day-trade guard of SPEC 9.2, off by default: never exit on the entry day.</summary>
|
||||||
|
public bool PdtGuard { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Sessions after the entry in which an earnings report keeps the strategy out.</summary>
|
||||||
|
public int EarningsSessions { get; init; } = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <c>equity_meanrev</c> (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.
|
||||||
|
/// </summary>
|
||||||
|
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 IReadOnlyList<DecisionTime> Schedule() => [DecisionTime.AfterClose];
|
||||||
|
|
||||||
|
/// <summary>The first 100 stocks of the universe of 8.2, in its order, that close above their 200-session average.</summary>
|
||||||
|
public IReadOnlyList<string> Universe(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<Intent> Decide(StrategyContext context)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(context);
|
||||||
|
var equity = context.Portfolio.Equity;
|
||||||
|
var intents = new List<Intent>();
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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).
|
||||||
|
/// </summary>
|
||||||
|
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 IReadOnlyList<ParameterSpec> Parameters =>
|
||||||
|
[
|
||||||
|
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"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,264 @@
|
|||||||
|
namespace Anubis.Strategies;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The indicators of the strategies (SPEC 8), written in house (SPEC 2.7). Each reads a <see cref="BarSeries"/> 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.
|
||||||
|
/// </summary>
|
||||||
|
public static class Indicators
|
||||||
|
{
|
||||||
|
/// <summary>Simple average of the last <paramref name="length"/> closes.</summary>
|
||||||
|
public static double? Sma(BarSeries bars, int length) => Sma(bars, length, bars?.Count - 1 ?? -1);
|
||||||
|
|
||||||
|
/// <summary>Simple average of the <paramref name="length"/> closes ending at <paramref name="end"/>, included.</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Average true range: the simple average of the last <paramref name="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.
|
||||||
|
/// </summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Wilder's relative strength index on the closes. The smoothing starts from a plain average of the first
|
||||||
|
/// <paramref name="length"/> changes of a window of <see cref="RsiWarmUp"/> × length bars: older bars weigh less
|
||||||
|
/// than one part in a million, and the value does not depend on where the history starts.
|
||||||
|
/// </summary>
|
||||||
|
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)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Bars of history the RSI reads, in multiples of its length.</summary>
|
||||||
|
public const int RsiWarmUp = 50;
|
||||||
|
|
||||||
|
/// <summary>The last <paramref name="count"/> simple daily returns, oldest first; null when the history is shorter.</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Annualised volatility of the last <paramref name="count"/> daily returns: sample standard deviation times the
|
||||||
|
/// square root of the sessions in a year.
|
||||||
|
/// </summary>
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The return over <paramref name="length"/> sessions that ends <paramref name="skip"/> sessions before the last
|
||||||
|
/// bar: close[t − skip] / close[t − skip − length] − 1.
|
||||||
|
/// </summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Annualised volatility of a portfolio with the given weights, from the covariance of the last
|
||||||
|
/// <paramref name="count"/> daily returns of each instrument, aligned by day. Days missing for an instrument count
|
||||||
|
/// as no change. Null when no instrument has enough history.
|
||||||
|
/// </summary>
|
||||||
|
public static double? PortfolioVolatility(IReadOnlyList<(BarSeries Bars, double Weight)> holdings, int count, int periodsPerYear)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(holdings);
|
||||||
|
var series = new List<(Dictionary<DateOnly, double> Returns, double Weight)>();
|
||||||
|
var days = new SortedSet<DateOnly>();
|
||||||
|
foreach (var (bars, weight) in holdings)
|
||||||
|
{
|
||||||
|
if (weight == 0 || bars.Count < count + 1)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var map = new Dictionary<DateOnly, double>(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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Sample standard deviation (n − 1).</summary>
|
||||||
|
public static double StandardDeviation(IReadOnlyList<double> values)
|
||||||
|
{
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Highest close from <paramref name="from"/> to the last bar, both included.</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Sessions from <paramref name="from"/> to the last bar, both included.</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Median of the last <paramref name="count"/> traded values (close × volume, or the quote volume when known).</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -143,10 +143,11 @@ public sealed class MovingAverageCrossFamily : IStrategyFamily
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>The strategies the laboratory can test. The bot's own strategies join with Phase 5.</summary>
|
/// <summary>The strategies the laboratory can test: the three of the bot first, then the examples.</summary>
|
||||||
public static class StrategyCatalog
|
public static class StrategyCatalog
|
||||||
{
|
{
|
||||||
public static IReadOnlyList<IStrategyFamily> All { get; } = [MovingAverageCrossFamily.Instance, BuyAndHoldFamily.Instance];
|
public static IReadOnlyList<IStrategyFamily> All { get; } =
|
||||||
|
[CryptoTrendFamily.Instance, EquityMomentumFamily.Instance, EquityMeanrevFamily.Instance, MovingAverageCrossFamily.Instance, BuyAndHoldFamily.Instance];
|
||||||
|
|
||||||
public static IStrategyFamily? Find(string id) => All.FirstOrDefault(f => f.Id == id);
|
public static IStrategyFamily? Find(string id) => All.FirstOrDefault(f => f.Id == id);
|
||||||
}
|
}
|
||||||
@@ -28,6 +28,27 @@ public sealed record Intent(string Symbol, decimal? TargetWeight, string Reason)
|
|||||||
{
|
{
|
||||||
public decimal? Stop { get; init; }
|
public decimal? Stop { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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 <see cref="Stop"/> is given or the position already has a stop.
|
||||||
|
/// </summary>
|
||||||
|
public decimal? StopOffset { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// An exit to carry out at this close rather than at the next open: <c>equity_meanrev</c> sells at 15:55 live,
|
||||||
|
/// which the daily backtest reads as the close (SPEC 8.3).
|
||||||
|
/// </summary>
|
||||||
|
public bool AtClose { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public IReadOnlyList<string> Adjustments { get; init; } = [];
|
||||||
|
|
||||||
|
/// <summary>The same intent with one more adjustment code.</summary>
|
||||||
|
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})");
|
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;
|
public double Volume(int index) => Bar(index).Volume;
|
||||||
|
|
||||||
|
/// <summary>Value traded in the session, in the quote currency: the source's own figure, or close × volume.</summary>
|
||||||
|
public double Value(int index)
|
||||||
|
{
|
||||||
|
var bar = Bar(index);
|
||||||
|
return bar.QuoteVolume ?? (bar.Close * bar.Volume);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The real close of the session, as traded that day, not adjusted to today.</summary>
|
||||||
|
public double RealClose(int index) => Bar(index).Close;
|
||||||
|
|
||||||
|
/// <summary>Index of the last bar on or before <paramref name="day"/>; −1 when there is none.</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The first day of the history; null when there is none.</summary>
|
||||||
|
public DateOnly? FirstDay => Count > 0 ? _bars[0].Day : null;
|
||||||
|
|
||||||
|
/// <summary>The day of the last bar; null when there is none.</summary>
|
||||||
|
public DateOnly? LastDay => Count > 0 ? _bars[Count - 1].Day : null;
|
||||||
|
|
||||||
/// <summary>The last <paramref name="length"/> closes, oldest first (fewer when the history is shorter).</summary>
|
/// <summary>The last <paramref name="length"/> closes, oldest first (fewer when the history is shorter).</summary>
|
||||||
public double[] Closes(int length)
|
public double[] Closes(int length)
|
||||||
{
|
{
|
||||||
@@ -115,8 +172,22 @@ public sealed class BarSeries
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>What a strategy may read to choose its instruments for a decision.</summary>
|
/// <summary>
|
||||||
public sealed record UniverseContext(DateOnly Day, IReadOnlyList<string> Available);
|
/// 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, <see cref="Members"/> gives the universes chosen and saved "as of a date" (SPEC 6.7).
|
||||||
|
/// </summary>
|
||||||
|
public sealed record UniverseContext(DateOnly Day, IReadOnlyList<string> Available)
|
||||||
|
{
|
||||||
|
public Func<string, BarSeries> Bars { get; init; } = _ => BarSeries.Empty;
|
||||||
|
|
||||||
|
public Func<string, InstrumentSpec?> Spec { get; init; } = _ => null;
|
||||||
|
|
||||||
|
/// <summary>Median spread of the last 30 days in basis points, live only; null in a backtest (no history).</summary>
|
||||||
|
public Func<string, double?>? SpreadBp { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The saved universe of a strategy on a date, live; null means "compute it from the bars".</summary>
|
||||||
|
public Func<string, DateOnly, IReadOnlyList<string>?>? Members { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>Named numeric parameters of a strategy variant. Values are decimal so a grid is written exactly.</summary>
|
/// <summary>Named numeric parameters of a strategy variant. Values are decimal so a grid is written exactly.</summary>
|
||||||
public sealed class StrategyParameters
|
public sealed class StrategyParameters
|
||||||
@@ -169,8 +240,45 @@ public sealed class StrategyContext(
|
|||||||
public BarSeries Bars(string symbol) => bars(symbol);
|
public BarSeries Bars(string symbol) => bars(symbol);
|
||||||
|
|
||||||
public InstrumentSpec? Spec(string symbol) => spec(symbol);
|
public InstrumentSpec? Spec(string symbol) => spec(symbol);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The next session of the market calendar after <see cref="Day"/>. Calendars are published in advance, so this
|
||||||
|
/// is not looking ahead: <c>equity_momentum</c> uses it to find the last session before a new week.
|
||||||
|
/// </summary>
|
||||||
|
public DateOnly? NextSession { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public decimal ReferenceEquity
|
||||||
|
{
|
||||||
|
get => _reference ?? Portfolio.Equity;
|
||||||
|
init => _reference = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly decimal? _reference;
|
||||||
|
|
||||||
|
/// <summary>Sessions in a year for this market: 365 for crypto, 252 for stocks.</summary>
|
||||||
|
public int PeriodsPerYear { get; init; } = 365;
|
||||||
|
|
||||||
|
/// <summary>Next earnings date of a stock, live and when the calendar has it; null in a backtest (SPEC 8.3).</summary>
|
||||||
|
public Func<string, DateOnly?>? NextEarnings { get; init; }
|
||||||
|
|
||||||
|
/// <summary>A restriction from the news on the instrument (SPEC 10.5, Phase 7); null in a backtest.</summary>
|
||||||
|
public Func<string, bool>? Restricted { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public IReadOnlyList<EquityMark> History { get; init; } = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>The equity at a close and the part of it in positions.</summary>
|
||||||
|
public sealed record EquityMark(DateOnly Day, decimal Equity, decimal Invested);
|
||||||
|
|
||||||
/// <summary>A trading strategy (SPEC 5.3): a function of the data up to "now" and of its own book, nothing else.</summary>
|
/// <summary>A trading strategy (SPEC 5.3): a function of the data up to "now" and of its own book, nothing else.</summary>
|
||||||
public interface IStrategy
|
public interface IStrategy
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Db;
|
||||||
|
|
||||||
|
namespace Anubis.Trading;
|
||||||
|
|
||||||
|
/// <summary>Stages of a decision (SPEC 5.2), in the order they are crossed.</summary>
|
||||||
|
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";
|
||||||
|
|
||||||
|
/// <summary>The one-step comparison of SPEC 12.3: live intents against the backtest restarted from the recorded state.</summary>
|
||||||
|
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";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A row of the decisions table: a stage, its outcome, its reason codes and the numbers it used.</summary>
|
||||||
|
public sealed record DecisionRow(Guid DecisionId, string Strategy, Guid? AccountId, string? Symbol, string Stage, string Outcome, IReadOnlyList<string> Reasons,
|
||||||
|
IReadOnlyDictionary<string, object?>? Data, DateTimeOffset At);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
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 Task<int> WriteAsync(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));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Every stage of one decision, in order.</summary>
|
||||||
|
public Task<List<DecisionRow>> 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);
|
||||||
|
|
||||||
|
/// <summary>The latest rows of a strategy, or of every strategy, newest first.</summary>
|
||||||
|
public Task<List<DecisionRow>> 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<Dictionary<string, object?>>(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<List<string>>(r.Text("reasons")) ?? [], data, r.Moment("created_at"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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();
|
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),
|
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),
|
||||||
|
|||||||
@@ -15,6 +15,14 @@ public sealed record TradeIntent(Guid InstrumentId, string Strategy, OrderSide S
|
|||||||
public decimal? StopLevel { get; init; }
|
public decimal? StopLevel { get; init; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>What the risk engine says of an intent: the quantity allowed (never more than asked), or why it is refused.</summary>
|
||||||
|
public sealed record GateResult(decimal Quantity, string? Refusal, IReadOnlyList<string> Reasons)
|
||||||
|
{
|
||||||
|
public static GateResult Pass(decimal quantity) => new(quantity, null, []);
|
||||||
|
|
||||||
|
public static GateResult Refuse(string reason) => new(0m, reason, [reason]);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>The account an order manager works on.</summary>
|
/// <summary>The account an order manager works on.</summary>
|
||||||
public sealed record AccountContext(Guid AccountId, string Name, string Broker, string Environment, string Currency);
|
public sealed record AccountContext(Guid AccountId, string Name, string Broker, string Environment, string Currency);
|
||||||
|
|
||||||
@@ -127,6 +135,21 @@ public sealed partial class OrderManager : IDisposable
|
|||||||
/// <summary>Called after new fills are recorded: the equity is photographed at every execution (SPEC 7.5).</summary>
|
/// <summary>Called after new fills are recorded: the equity is photographed at every execution (SPEC 7.5).</summary>
|
||||||
public Func<CancellationToken, Task>? AfterFills { get; init; }
|
public Func<CancellationToken, Task>? AfterFills { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public Func<TradeIntent, AccountContext, CancellationToken, Task<GateResult>>? Gate { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public Func<TradeIntent, AccountContext, CancellationToken, Task<string?>>? LivePermit { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The technical check of a purchase's limit against the last valid price (SPEC 9.2): a reason refuses it.</summary>
|
||||||
|
public Func<decimal, Quote, string?>? PurchasePriceCheck { get; init; }
|
||||||
|
|
||||||
public AccountContext Account => _account;
|
public AccountContext Account => _account;
|
||||||
|
|
||||||
public IBrokerAccount Broker => _broker;
|
public IBrokerAccount Broker => _broker;
|
||||||
@@ -155,6 +178,29 @@ public sealed partial class OrderManager : IDisposable
|
|||||||
return (null, OrderReasons.PrudentMode);
|
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 id = Ids.NewId(_clock);
|
||||||
var now = _clock.UtcNow;
|
var now = _clock.UtcNow;
|
||||||
await _db.WriteAsync(s => s.ExecuteAsync(
|
await _db.WriteAsync(s => s.ExecuteAsync(
|
||||||
@@ -327,6 +373,55 @@ public sealed partial class OrderManager : IDisposable
|
|||||||
_db.ReadAsync<IReadOnlyList<(string, Guid, OrderPurpose)>>(async s => (await s.QueryAsync(OrderSelect + " WHERE account_id = @a AND status IN ('submitted', 'partially_filled')",
|
_db.ReadAsync<IReadOnlyList<(string, Guid, OrderPurpose)>>(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);
|
ReadOrder, ("a", _account.AccountId)).ConfigureAwait(false)).Select(o => (o.ClientOrderId, o.InstrumentId, o.Purpose)).ToList(), cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<int> CancelWorkingAsync(string reason, Func<string, bool>? 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<string?> 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<bool> IsPrudentAsync(CancellationToken cancellationToken) =>
|
public Task<bool> 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,
|
_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);
|
cancellationToken);
|
||||||
@@ -500,6 +595,19 @@ public sealed partial class OrderManager : IDisposable
|
|||||||
return;
|
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 sequence = exec.Sequence + 1;
|
||||||
var clientId = ClientOrderIds.Build(_installation, _account.Environment, exec.Strategy, exec.Purpose, exec.Key, sequence);
|
var clientId = ClientOrderIds.Build(_installation, _account.Environment, exec.Strategy, exec.Purpose, exec.Key, sequence);
|
||||||
var now = _clock.UtcNow;
|
var now = _clock.UtcNow;
|
||||||
|
|||||||
@@ -0,0 +1,617 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Db;
|
||||||
|
using Anubis.Risk;
|
||||||
|
|
||||||
|
namespace Anubis.Trading;
|
||||||
|
|
||||||
|
/// <summary>A world as the risk engine sees it now: what it remembers, the three measures, the multiplier on purchases.</summary>
|
||||||
|
public sealed record WorldRisk(string World, RiskMonitorState State, RiskMeasures Measures, decimal Multiplier, bool EntriesBlocked);
|
||||||
|
|
||||||
|
/// <summary>Exposure of the bot in euro, from the ledgers: equity and invested per world, crypto everywhere. Twins are left out.</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What the bot as a whole remembers: a "stop and close all" still waiting for markets to open.</summary>
|
||||||
|
public sealed record BotRiskState
|
||||||
|
{
|
||||||
|
public bool CloseAll { get; init; }
|
||||||
|
|
||||||
|
public DateTimeOffset? CloseAllSince { get; init; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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
|
||||||
|
/// <c>/data/STOP</c>, and restarts only on the user's confirmation (9.3). Protection always passes.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class RiskEngine(Database db, IClock clock, Ledger ledger, StageBook stages, SettingsStore settings, FxStore fx,
|
||||||
|
Func<Guid, CancellationToken, Task<Instrument?>> instruments, Func<string, CancellationToken, Task<Quote?>> 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");
|
||||||
|
|
||||||
|
/// <summary>The file that stops the bot (SPEC 9.3): <c>/data/STOP</c> in Docker, the data folder on desktop.</summary>
|
||||||
|
public string? StopFile { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The clock skew measured with a broker, when known (SPEC 9.2): beyond the limit no new entries.</summary>
|
||||||
|
public Func<string, TimeSpan?>? ClockSkew { get; init; }
|
||||||
|
|
||||||
|
public bool StopRequested => StopFile is { } path && File.Exists(path);
|
||||||
|
|
||||||
|
/// <summary>The gate of the order manager: the verdict on an intent, written to the decisions table (SPEC 5.2).</summary>
|
||||||
|
public async Task<GateResult> GateAsync(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<string, object?> Data)> DecideAsync(TradeIntent intent, AccountContext account, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var data = new Dictionary<string, object?>(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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The state of a world with its measures now.</summary>
|
||||||
|
public async Task<WorldRisk> WorldAsync(string world, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var state = await LoadAsync<RiskMonitorState>(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));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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 <c>/data/STOP</c>; a "stop and close all" waiting for the open.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<IReadOnlyList<RiskAlert>> CheckAsync(IReadOnlyCollection<OrderManager> managers, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(managers);
|
||||||
|
var alerts = new List<RiskAlert>();
|
||||||
|
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<RiskMonitorState>(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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// "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.
|
||||||
|
/// </summary>
|
||||||
|
public async Task StopAllAsync(IReadOnlyCollection<OrderManager> managers, 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// "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.
|
||||||
|
/// </summary>
|
||||||
|
public async Task CloseAllAsync(IReadOnlyCollection<OrderManager> managers, 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Sends the sales of a "stop and close all" whose market is now open. Returns how many positions are still waiting.</summary>
|
||||||
|
public async Task<int> ContinueCloseAllAsync(IReadOnlyCollection<OrderManager> managers, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(managers);
|
||||||
|
if (await LoadAsync<BotRiskState>(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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
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<RiskMonitorState>(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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>True when the switch of at least one world tripped and waits for the user (SPEC 9.3).</summary>
|
||||||
|
public async Task<bool> AnyTrippedAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
foreach (var world in new[] { Worlds.Simulated, Worlds.Real })
|
||||||
|
{
|
||||||
|
if (await LoadAsync<RiskMonitorState>(world, cancellationToken).ConfigureAwait(false) is { Tripped: true })
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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).
|
||||||
|
/// </summary>
|
||||||
|
public async Task<RiskExposure> ExposureAsync(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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<decimal> ReferenceAsync(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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What the bot as a whole remembers: a "stop and close all" still waiting for the open.</summary>
|
||||||
|
public async Task<BotRiskState> BotAsync(CancellationToken cancellationToken) =>
|
||||||
|
await LoadAsync<BotRiskState>(BotRow, cancellationToken).ConfigureAwait(false) ?? new BotRiskState();
|
||||||
|
|
||||||
|
/// <summary>The risk events, newest first, for the Rischio screen.</summary>
|
||||||
|
public Task<List<(DateTimeOffset At, string Kind, string Severity, string Message, string? World)>> 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);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<int> PdtRoomAsync(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<OrderManager> 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<List<IndexPoint>> 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<Dictionary<Guid, (string Environment, string Currency)>> 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<HashSet<(Guid, string)>> TwinsAsync(CancellationToken cancellationToken) =>
|
||||||
|
[.. (await stages.AllAsync(cancellationToken).ConfigureAwait(false)).Where(s => s.HasTwin && s.AccountId is not null).Select(s => (s.AccountId!.Value, s.Strategy))];
|
||||||
|
|
||||||
|
private async Task<CarriedResults> CarriedAsync(string strategy, CancellationToken cancellationToken) =>
|
||||||
|
CarriedResults.Parse(await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT state FROM strategy_state WHERE strategy = @s", r => r.TextOrNull("state"), ("s", strategy)),
|
||||||
|
cancellationToken).ConfigureAwait(false));
|
||||||
|
|
||||||
|
private async Task<decimal?> UsdRateAsync(CancellationToken cancellationToken) =>
|
||||||
|
(await fx.LatestAsync("EUR", "USD", cancellationToken).ConfigureAwait(false))?.Rate;
|
||||||
|
|
||||||
|
private async Task<T?> LoadAsync<T>(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<T>(json, Json);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task SaveAsync<T>(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);
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
|
||||||
|
/// <summary>The stages of SPEC 12.3. The stage decides where a strategy's orders go (SPEC 7.1).</summary>
|
||||||
|
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 IReadOnlyList<string> All = [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,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>A strategy in reduced real works with a quarter of its capital (SPEC 12.3).</summary>
|
||||||
|
public const decimal ReducedShare = 0.25m;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The backtest outcome a strategy qualified with (SPEC 12.3): it travels with the code in <c>docs/backtests/</c>
|
||||||
|
/// and the requirements and demotions compare against it. It does not move when estimates are updated (11.6).
|
||||||
|
/// </summary>
|
||||||
|
public sealed record Qualification
|
||||||
|
{
|
||||||
|
public required bool Passed { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Why it passed or not, in plain Italian.</summary>
|
||||||
|
public required string Verdict { get; init; }
|
||||||
|
|
||||||
|
/// <summary>The report it comes from: a file of <c>docs/backtests/</c> and the plan's hash.</summary>
|
||||||
|
public required string Report { get; init; }
|
||||||
|
|
||||||
|
public string? PlanHash { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The parameters of the variant that qualified, as the report writes them (<c>coin_vol=10;max_stop=20</c>): the
|
||||||
|
/// strategy runs live with these, so the figures it is compared with are those of the rules it follows.
|
||||||
|
/// </summary>
|
||||||
|
public string? Parameters { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Largest fall of the backtest, as a fraction of the capital used: 0.18 is −18%.</summary>
|
||||||
|
public decimal MaxDrawdown { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Slippage the backtest assumed, in basis points of the price.</summary>
|
||||||
|
public decimal ExpectedSlippageBp { get; init; }
|
||||||
|
|
||||||
|
/// <summary>Estimated round-trip cost, as a fraction of the value traded (fees and slippage, both ways).</summary>
|
||||||
|
public decimal RoundTripCost { get; init; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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%.
|
||||||
|
/// </summary>
|
||||||
|
public IReadOnlyList<double> ExpectedPathP5 { get; init; } = [];
|
||||||
|
|
||||||
|
public static readonly JsonSerializerOptions Json = new()
|
||||||
|
{
|
||||||
|
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
|
||||||
|
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A strategy where it stands: stage, accounts, capital, and whether it is only closing real positions.</summary>
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
/// <summary>Where the orders of a new decision go: nowhere in observation, the simulation account in simulation, the real one in reduced and real.</summary>
|
||||||
|
public Guid? OrdersAccount => Stage switch
|
||||||
|
{
|
||||||
|
StrategyStages.Observation => null,
|
||||||
|
StrategyStages.Simulation => AccountId,
|
||||||
|
_ => LiveAccountId,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>A strategy with real money keeps running in simulation too: the simulated twin (SPEC 12.3).</summary>
|
||||||
|
public bool HasTwin => StrategyStages.IsLive(Stage);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One requirement of SPEC 12.3, checked automatically and shown in the interface.</summary>
|
||||||
|
public sealed record Requirement(string Key, string Label, string Value, string Target, bool Met);
|
||||||
|
|
||||||
|
/// <summary>A condition of automatic demotion in progress (SPEC 12.3).</summary>
|
||||||
|
public sealed record DemotionCondition(string Key, string Message);
|
||||||
|
|
||||||
|
/// <summary>What the user confirms with the procedure of SPEC 12.4.</summary>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The results of the ledgers a strategy worked on, kept in the reference equity (SPEC 9.2) when it changes stage.
|
||||||
|
/// Each ledger has a baseline: the results already carried, or made while it was not the one taking the orders
|
||||||
|
/// (the twin's during real money). At a change the ledger being left carries what it made since its baseline,
|
||||||
|
/// times four from reduced real, and the ledger taking over starts from what it holds now. So a ledger that goes on
|
||||||
|
/// (reduced to real on the same account, the twin after a demotion) never counts the same result twice. Amounts
|
||||||
|
/// stay in the ledger's currency and become euro when the reference is computed.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record CarriedResults(IReadOnlyDictionary<Guid, decimal> Carried, IReadOnlyDictionary<Guid, decimal> Baselines)
|
||||||
|
{
|
||||||
|
public static CarriedResults Empty { get; } = new(new Dictionary<Guid, decimal>(), new Dictionary<Guid, decimal>());
|
||||||
|
|
||||||
|
public decimal Baseline(Guid account) => Baselines.TryGetValue(account, out var b) ? b : 0m;
|
||||||
|
|
||||||
|
public static CarriedResults Parse(string? state)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(state) || System.Text.Json.Nodes.JsonNode.Parse(state) is not System.Text.Json.Nodes.JsonObject node)
|
||||||
|
{
|
||||||
|
return Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Dictionary<Guid, decimal> Map(System.Text.Json.Nodes.JsonNode? n) =>
|
||||||
|
n is System.Text.Json.Nodes.JsonObject o
|
||||||
|
? o.Where(p => Guid.TryParse(p.Key, out _) && p.Value is not null).ToDictionary(p => Guid.Parse(p.Key), p => p.Value!.GetValue<decimal>())
|
||||||
|
: [];
|
||||||
|
|
||||||
|
return new CarriedResults(Map(node["carried"]), Map(node["baselines"]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Stages of the strategies (SPEC 12.3, 12.4, 7.1). The only way to real money is <see cref="ConfirmLiveAsync"/>:
|
||||||
|
/// the startup consent, every requirement met, the confirmation phrase, the password and the second factor checked
|
||||||
|
/// right then. Every confirmation, revocation and demotion goes to the stage history and to the change log. A
|
||||||
|
/// strategy that leaves real money keeps its real positions in exit only until they are at zero.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class StageBook(Database db, IClock clock, TradingConsent consent, Func<string, string?, CancellationToken, Task<bool>> reauthenticate)
|
||||||
|
{
|
||||||
|
public const int ObservationDays = 90;
|
||||||
|
public const int SimulationDays = 60;
|
||||||
|
public const int ReducedDays = 30;
|
||||||
|
public const int IncidentDays = 30;
|
||||||
|
public const decimal MaxOneStepDifference = 0.02m;
|
||||||
|
|
||||||
|
private static readonly CultureInfo Italian = CultureInfo.GetCultureInfo("it-IT");
|
||||||
|
|
||||||
|
public static int MinClosedTrades(string strategy) => strategy switch
|
||||||
|
{
|
||||||
|
StrategyNames.CryptoTrend => 8,
|
||||||
|
StrategyNames.EquityMomentum => 10,
|
||||||
|
StrategyNames.EquityMeanrev => 30,
|
||||||
|
_ => 30,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>The phrase the user types to confirm (SPEC 12.4): it names the strategy and the stage.</summary>
|
||||||
|
public static string Phrase(string strategy, string stage) =>
|
||||||
|
$"confermo soldi veri per {strategy} in {StrategyStages.Label(stage)}";
|
||||||
|
|
||||||
|
public async Task<IReadOnlyList<StrategyStage>> AllAsync(CancellationToken cancellationToken) =>
|
||||||
|
await db.ReadAsync(s => s.QueryAsync(Select + " ORDER BY strategy", Read), cancellationToken).ConfigureAwait(false);
|
||||||
|
|
||||||
|
public Task<StrategyStage?> GetAsync(string strategy, CancellationToken cancellationToken) =>
|
||||||
|
db.ReadAsync(s => s.FirstOrDefaultAsync(Select + " WHERE strategy = @s", Read, ("s", strategy)), cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The permission on a real account (SPEC 12.4), asked by the order manager when an intent arrives and again right
|
||||||
|
/// before the order leaves. Null allows it. Protection of what the bot holds there always goes; an exit-only
|
||||||
|
/// strategy may only sell; everything else needs reduced or real with a confirmation, on that very account.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<string?> LiveRefusalAsync(TradeIntent intent, AccountContext account, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(intent);
|
||||||
|
ArgumentNullException.ThrowIfNull(account);
|
||||||
|
if (account.Environment != TradingEnvironments.Live)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!consent.AllowLive)
|
||||||
|
{
|
||||||
|
return RiskReasons.NoConsent;
|
||||||
|
}
|
||||||
|
|
||||||
|
var stage = await GetAsync(intent.Strategy, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (stage is null || stage.LiveAccountId != account.AccountId)
|
||||||
|
{
|
||||||
|
return RiskReasons.LiveNotConfirmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (intent.Purpose is OrderPurpose.Protective or OrderPurpose.Stop)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stage.ExitOnly)
|
||||||
|
{
|
||||||
|
return intent.Purpose == OrderPurpose.Exit && intent.Side == OrderSide.Sell ? null : RiskReasons.ExitOnly;
|
||||||
|
}
|
||||||
|
|
||||||
|
return StrategyStages.IsLive(stage.Stage) && stage.LiveConfirmedAt is not null ? null : RiskReasons.LiveNotConfirmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The backtest outcome loaded at first start (SPEC 12.3): a base strategy that passed starts in simulation, one
|
||||||
|
/// that did not stays in observation and the interface says why. A strategy that already moved keeps its stage.
|
||||||
|
/// </summary>
|
||||||
|
public async Task ApplyQualificationAsync(string strategy, Qualification qualification, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(qualification);
|
||||||
|
var json = new DbJson(JsonSerializer.Serialize(qualification, Qualification.Json));
|
||||||
|
await db.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
var current = await s.FirstOrDefaultAsync("SELECT stage, stage_since FROM strategy_state WHERE strategy = @s",
|
||||||
|
r => (Stage: r.Text("stage"), Since: r.MomentOrNull("stage_since")), ("s", strategy)).ConfigureAwait(false);
|
||||||
|
// With real money in play the figures a strategy qualified with do not move (SPEC 12.3): a new build cannot
|
||||||
|
// change the thresholds of its demotion. It gets the new outcome when it is back in simulation.
|
||||||
|
if (current == default || StrategyStages.IsLive(current.Stage))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await s.ExecuteAsync("UPDATE strategy_state SET qualification = @q, updated_at = @t WHERE strategy = @s", cancellationToken,
|
||||||
|
("q", json), ("t", clock.UtcNow), ("s", strategy)).ConfigureAwait(false);
|
||||||
|
var moved = await s.CountAsync("SELECT COUNT(*) FROM strategy_stage_history WHERE strategy = @s", ("s", strategy)).ConfigureAwait(false) > 0;
|
||||||
|
if (moved || current.Stage != StrategyStages.Observation)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (qualification.Passed)
|
||||||
|
{
|
||||||
|
await MoveCoreAsync(s, strategy, current.Stage, StrategyStages.Simulation, "backtest_passed", "primo avvio", cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await s.ExecuteAsync("UPDATE strategy_state SET stage_reason = @r, stage_since = COALESCE(stage_since, @t), updated_at = @t WHERE strategy = @s", cancellationToken,
|
||||||
|
("r", "backtest_not_passed"), ("t", clock.UtcNow), ("s", strategy)).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Moves a strategy between observation and simulation (the user's choice from the interface). Real money is
|
||||||
|
/// never reached this way: only <see cref="ConfirmLiveAsync"/> does it.
|
||||||
|
/// </summary>
|
||||||
|
public async Task MoveAsync(string strategy, string to, string reason, string by, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (to is not (StrategyStages.Observation or StrategyStages.Simulation))
|
||||||
|
{
|
||||||
|
throw new LiveConfirmationException("procedure", "Per i soldi veri serve la procedura di conferma.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var current = await GetAsync(strategy, cancellationToken).ConfigureAwait(false) ?? throw new ArgumentException("Strategia sconosciuta: " + strategy, nameof(strategy));
|
||||||
|
if (StrategyStages.IsLive(current.Stage))
|
||||||
|
{
|
||||||
|
await RevokeAsync(strategy, by, reason, cancellationToken).ConfigureAwait(false);
|
||||||
|
current = (await GetAsync(strategy, cancellationToken).ConfigureAwait(false))!;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (current.Stage == to)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// From observation to simulation (SPEC 12.3): the protocol passed on the history and at least 90 days of signals
|
||||||
|
// collected live. The first start moves a base strategy that passed without this, as the specification says.
|
||||||
|
if (to == StrategyStages.Simulation && current.Stage == StrategyStages.Observation)
|
||||||
|
{
|
||||||
|
if (current.Qualification is not { Passed: true })
|
||||||
|
{
|
||||||
|
throw new LiveConfirmationException("backtest", "La strategia non ha superato il protocollo sui dati storici: resta in osservazione.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ObservedDays(current) < ObservationDays)
|
||||||
|
{
|
||||||
|
throw new LiveConfirmationException("observation", $"Servono almeno {ObservationDays} giorni di segnali raccolti dal vivo in osservazione.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.WriteAsync(s => MoveCoreAsync(s, strategy, current.Stage, to, reason, by, cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The requirements of SPEC 12.3 for the next step towards real money, with their values now.</summary>
|
||||||
|
public async Task<IReadOnlyList<Requirement>> RequirementsAsync(string strategy, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var stage = await GetAsync(strategy, cancellationToken).ConfigureAwait(false) ?? throw new ArgumentException("Strategia sconosciuta: " + strategy, nameof(strategy));
|
||||||
|
var now = clock.UtcNow;
|
||||||
|
var since = stage.StageSince ?? now;
|
||||||
|
var list = new List<Requirement>();
|
||||||
|
var q = stage.Qualification;
|
||||||
|
list.Add(new("backtest", "Protocollo di verifica sui dati storici", q is null ? "mancante" : q.Passed ? "superato" : "non superato", "superato", q?.Passed == true));
|
||||||
|
if (stage.Stage == StrategyStages.Observation)
|
||||||
|
{
|
||||||
|
var observed = ObservedDays(stage);
|
||||||
|
list.Add(new("observation", "Giorni di segnali raccolti dal vivo", observed.ToString(Italian), $"almeno {ObservationDays}", observed >= ObservationDays));
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stage.Stage == StrategyStages.Reduced)
|
||||||
|
{
|
||||||
|
var days = (int)(now - since).TotalDays;
|
||||||
|
list.Add(new("days", "Giorni in reale ridotto", days.ToString(Italian), $"almeno {ReducedDays}", days >= ReducedDays));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var days = stage.Stage == StrategyStages.Simulation ? (int)(now - since).TotalDays : 0;
|
||||||
|
list.Add(new("days", "Giorni in simulazione", days.ToString(Italian), $"almeno {SimulationDays}", days >= SimulationDays));
|
||||||
|
var trades = await ClosedTradesAsync(strategy, stage.AccountId, since, cancellationToken).ConfigureAwait(false);
|
||||||
|
var minimum = MinClosedTrades(strategy);
|
||||||
|
list.Add(new("trades", "Operazioni chiuse", trades.Count.ToString(Italian), $"almeno {minimum}", trades.Count >= minimum));
|
||||||
|
var oneStep = await OneStepAsync(strategy, since, cancellationToken).ConfigureAwait(false);
|
||||||
|
list.Add(new("one_step", "Coerenza con il backtest (confronto a un passo)",
|
||||||
|
oneStep is { } share ? Format.Percent(share * 100m, 1) : "da misurare", "sotto il 2%", oneStep is { } d && d < MaxOneStepDifference));
|
||||||
|
var slippage = await SlippageAsync(stage.AccountId, since, cancellationToken).ConfigureAwait(false);
|
||||||
|
var simulator = await EnvironmentOfAsync(stage.AccountId, cancellationToken).ConfigureAwait(false) == TradingEnvironments.Simulation;
|
||||||
|
var expected = q?.ExpectedSlippageBp ?? 0m;
|
||||||
|
list.Add(new("slippage", "Prezzi ottenuti rispetto al previsto",
|
||||||
|
simulator ? "uguali per costruzione (simulatore interno)" : slippage is { } bp ? Format.Quantity(Math.Round(bp, 1)) + " punti base" : "nessuna esecuzione",
|
||||||
|
$"al massimo {Format.Quantity(expected * 2m)} punti base", simulator || (slippage is { } b && b <= expected * 2m)));
|
||||||
|
if (strategy == StrategyNames.EquityMeanrev)
|
||||||
|
{
|
||||||
|
list.Add(MeanrevEdge(trades, q?.RoundTripCost ?? 0m));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var incidents = await CriticalIncidentsAsync(now - TimeSpan.FromDays(IncidentDays), cancellationToken).ConfigureAwait(false);
|
||||||
|
list.Add(new("incidents", "Incidenti critici negli ultimi 30 giorni", incidents.ToString(Italian), "nessuno", incidents == 0));
|
||||||
|
var demotions = StrategyStages.IsLive(stage.Stage) ? await DemotionConditionsAsync(stage, cancellationToken).ConfigureAwait(false) : [];
|
||||||
|
list.Add(new("demotion", "Condizioni di retrocessione in corso", demotions.Count == 0 ? "nessuna" : string.Join("; ", demotions.Select(d => d.Message)), "nessuna",
|
||||||
|
demotions.Count == 0));
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The procedure of SPEC 12.4: from simulation to reduced real, or from reduced to real. It is refused unless the
|
||||||
|
/// startup configuration allows real money, the account is a real account of the strategy's broker, every
|
||||||
|
/// requirement is met, the phrase is typed as shown and the password and second factor are right now.
|
||||||
|
/// </summary>
|
||||||
|
public async Task ConfirmLiveAsync(LiveConfirmation c, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(c);
|
||||||
|
if (!consent.AllowLive)
|
||||||
|
{
|
||||||
|
throw new LiveConfirmationException(RiskReasons.NoConsent,
|
||||||
|
$"La configurazione d'avvio non consente i soldi veri ({consent.Source}): la procedura non può partire.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var stage = await GetAsync(c.Strategy, cancellationToken).ConfigureAwait(false) ?? throw new ArgumentException("Strategia sconosciuta: " + c.Strategy, nameof(c));
|
||||||
|
var to = stage.Stage switch
|
||||||
|
{
|
||||||
|
StrategyStages.Simulation => StrategyStages.Reduced,
|
||||||
|
StrategyStages.Reduced => StrategyStages.Real,
|
||||||
|
_ => throw new LiveConfirmationException("stage", $"Da {StrategyStages.Label(stage.Stage)} non si passa ai soldi veri."),
|
||||||
|
};
|
||||||
|
var account = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT broker, environment FROM accounts WHERE id = @id",
|
||||||
|
r => (Broker: r.Text("broker"), Environment: r.Text("environment")), ("id", c.LiveAccountId)), cancellationToken).ConfigureAwait(false);
|
||||||
|
if (account == default || account.Environment != TradingEnvironments.Live || account.Broker != StrategyNames.BrokerOf(c.Strategy))
|
||||||
|
{
|
||||||
|
throw new LiveConfirmationException("account", "Il conto scelto non è il conto reale del broker di questa strategia.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stage.Stage == StrategyStages.Reduced && stage.LiveAccountId != c.LiveAccountId)
|
||||||
|
{
|
||||||
|
throw new LiveConfirmationException("account", "Il passaggio a reale avviene sullo stesso conto del reale ridotto.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var unmet = (await RequirementsAsync(c.Strategy, cancellationToken).ConfigureAwait(false)).Where(r => !r.Met).ToList();
|
||||||
|
if (unmet.Count > 0)
|
||||||
|
{
|
||||||
|
throw new LiveConfirmationException("requirements", "Requisiti non ancora soddisfatti: " + string.Join(", ", unmet.Select(r => r.Label.ToLowerInvariant())) + ".");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.Equals(c.Phrase.Trim(), Phrase(c.Strategy, to), StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
throw new LiveConfirmationException("phrase", "La frase di conferma non corrisponde: scrivila esattamente come appare.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!await reauthenticate(c.Password, c.Code, cancellationToken).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
throw new LiveConfirmationException("password", "Password o codice a due fattori non corretti.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var now = clock.UtcNow;
|
||||||
|
await db.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
await CarryResultsAsync(s, stage, c.LiveAccountId, cancellationToken).ConfigureAwait(false);
|
||||||
|
await s.ExecuteAsync("UPDATE strategy_state SET live_account_id = @a, live_confirmed_at = @t, live_confirmed_by = @by, exit_only = @no, updated_at = @t WHERE strategy = @s",
|
||||||
|
cancellationToken, ("a", c.LiveAccountId), ("t", now), ("by", c.By), ("no", false), ("s", c.Strategy)).ConfigureAwait(false);
|
||||||
|
await MoveCoreAsync(s, c.Strategy, stage.Stage, to, "confirmed_12_4", c.By, cancellationToken).ConfigureAwait(false);
|
||||||
|
await LogChangeAsync(s, c.Strategy, stage.Stage, to, c.By, cancellationToken).ConfigureAwait(false);
|
||||||
|
}, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The phrase that confirms more risk while real money is in play.</summary>
|
||||||
|
public const string RaisePhrase = "confermo più rischio con soldi veri";
|
||||||
|
|
||||||
|
/// <summary>True when a strategy, of <paramref name="broker"/> or of any broker when null, is in reduced or real.</summary>
|
||||||
|
public async Task<bool> AnyLiveAsync(string? broker, CancellationToken cancellationToken) =>
|
||||||
|
(await AllAsync(cancellationToken).ConfigureAwait(false)).Any(s => StrategyStages.IsLive(s.Stage) && (broker is null || StrategyNames.BrokerOf(s.Strategy) == broker));
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Raising a risk limit or the capital while a strategy has real money needs the confirmation of SPEC 12.4: the
|
||||||
|
/// typed phrase and a fresh password and second factor. Without real money in play it passes as it is.
|
||||||
|
/// </summary>
|
||||||
|
public async Task ConfirmRaiseAsync(string? broker, string? phrase, string? password, string? code, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (!await AnyLiveAsync(broker, cancellationToken).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.Equals(phrase?.Trim(), RaisePhrase, StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
throw new LiveConfirmationException("phrase", $"Con soldi veri in gioco, per alzare un limite scrivi \"{RaisePhrase}\".");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (password is null || !await reauthenticate(password, code, cancellationToken).ConfigureAwait(false))
|
||||||
|
{
|
||||||
|
throw new LiveConfirmationException("password", "Password o codice non corretti.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// More risk is refused while a strategy with real money has a demotion condition in progress (SPEC 12.4).
|
||||||
|
foreach (var live in (await AllAsync(cancellationToken).ConfigureAwait(false))
|
||||||
|
.Where(s => StrategyStages.IsLive(s.Stage) && (broker is null || StrategyNames.BrokerOf(s.Strategy) == broker)))
|
||||||
|
{
|
||||||
|
var conditions = await DemotionConditionsAsync(live, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (conditions.Count > 0 && conditions[0] is var condition)
|
||||||
|
{
|
||||||
|
throw new LiveConfirmationException("demotion", $"{StrategyNames.Label(live.Strategy, withMarket: false)} ha una condizione di retrocessione in corso: {condition.Message}.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private int ObservedDays(StrategyStage stage) =>
|
||||||
|
stage.Stage == StrategyStages.Observation && stage.StageSince is { } since ? Math.Max(0, (int)(clock.UtcNow - since).TotalDays) : 0;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The user takes real money away from a strategy (SPEC 12.3, 12.4): back to simulation, and the real positions,
|
||||||
|
/// if any, stay in exit only until they are at zero.
|
||||||
|
/// </summary>
|
||||||
|
public Task RevokeAsync(string strategy, string by, string reason, CancellationToken cancellationToken) =>
|
||||||
|
LeaveLiveAsync(strategy, by, reason, automatic: false, cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>Automatic demotion (SPEC 12.3): like a revocation, with an alert and a risk event.</summary>
|
||||||
|
public Task DemoteAsync(string strategy, string reason, CancellationToken cancellationToken) =>
|
||||||
|
LeaveLiveAsync(strategy, "automatico", reason, automatic: true, cancellationToken);
|
||||||
|
|
||||||
|
/// <summary>Demotes every strategy with real money that has a condition of SPEC 12.3 in progress. Returns those demoted.</summary>
|
||||||
|
public async Task<IReadOnlyList<string>> CheckDemotionsAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var demoted = new List<string>();
|
||||||
|
foreach (var stage in (await AllAsync(cancellationToken).ConfigureAwait(false)).Where(s => StrategyStages.IsLive(s.Stage)))
|
||||||
|
{
|
||||||
|
var conditions = await DemotionConditionsAsync(stage, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (conditions.Count > 0)
|
||||||
|
{
|
||||||
|
await DemoteAsync(stage.Strategy, conditions[0].Key, cancellationToken).ConfigureAwait(false);
|
||||||
|
demoted.Add(stage.Strategy);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return demoted;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An exit-only strategy whose real positions are all at zero goes back to normal: nothing is left to close.</summary>
|
||||||
|
public async Task<int> ReleaseExitOnlyAsync(Ledger ledger, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(ledger);
|
||||||
|
var released = 0;
|
||||||
|
foreach (var stage in (await AllAsync(cancellationToken).ConfigureAwait(false)).Where(s => s.ExitOnly && s.LiveAccountId is not null))
|
||||||
|
{
|
||||||
|
var open = (await ledger.PositionsAsync(stage.LiveAccountId, cancellationToken).ConfigureAwait(false)).Any(p => p.Strategy == stage.Strategy && p.Quantity > 0m);
|
||||||
|
if (open)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
await db.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
await s.ExecuteAsync("UPDATE strategy_state SET exit_only = @no, updated_at = @t WHERE strategy = @s", cancellationToken,
|
||||||
|
("no", false), ("t", clock.UtcNow), ("s", stage.Strategy)).ConfigureAwait(false);
|
||||||
|
await Diary.WriteAsync(s, clock, DiaryKinds.System, "exit_only_done",
|
||||||
|
$"{StrategyNames.Label(stage.Strategy, withMarket: true)}: tutte le posizioni reali sono chiuse, la sola uscita è finita.", null, cancellationToken).ConfigureAwait(false);
|
||||||
|
}, cancellationToken).ConfigureAwait(false);
|
||||||
|
released++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return released;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The conditions of automatic demotion of SPEC 12.3 in progress for a strategy with real money.</summary>
|
||||||
|
public async Task<IReadOnlyList<DemotionCondition>> DemotionConditionsAsync(StrategyStage stage, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(stage);
|
||||||
|
var list = new List<DemotionCondition>();
|
||||||
|
if (stage.LiveAccountId is not { } account || stage.Qualification is not { } q)
|
||||||
|
{
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
var since = stage.StageSince ?? clock.UtcNow;
|
||||||
|
var points = await db.ReadAsync(s => s.QueryAsync(
|
||||||
|
"SELECT taken_at, twr_index FROM equity_snapshots WHERE scope = 'strategy' AND account_id = @a AND strategy = @s AND taken_at >= @f ORDER BY taken_at",
|
||||||
|
r => (At: r.Moment("taken_at"), Index: r.MoneyOrNull("twr_index") ?? 1m), ("a", account), ("s", stage.Strategy), ("f", since)), cancellationToken).ConfigureAwait(false);
|
||||||
|
if (points.Count > 1)
|
||||||
|
{
|
||||||
|
var peak = points[0].Index;
|
||||||
|
var worst = 0m;
|
||||||
|
foreach (var p in points)
|
||||||
|
{
|
||||||
|
peak = Math.Max(peak, p.Index);
|
||||||
|
worst = Math.Min(worst, peak > 0m ? (p.Index / peak) - 1m : 0m);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (q.MaxDrawdown > 0m && -worst > 1.5m * q.MaxDrawdown)
|
||||||
|
{
|
||||||
|
list.Add(new("drawdown", $"calo {Format.Percent(worst * 100m, 1)}, oltre 1,5 volte quello del backtest ({Format.Percent(-q.MaxDrawdown * 100m, 1)})"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sessions below the 5th percentile of the expected path, counted back from the last day. Stocks have no
|
||||||
|
// session at the weekend: those days are left out, as in the bootstrap of their sessions.
|
||||||
|
var stocks = StrategyNames.BrokerOf(stage.Strategy) != Anubis.Data.Venues.Okx;
|
||||||
|
var daily = points.GroupBy(p => DateOnly.FromDateTime(p.At.UtcDateTime))
|
||||||
|
.Where(g => !stocks || g.Key.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday))
|
||||||
|
.Select(g => g.Last().Index).ToList();
|
||||||
|
var start = points[0].Index;
|
||||||
|
var below = 0;
|
||||||
|
for (var day = daily.Count - 1; day >= 1 && day - 1 < q.ExpectedPathP5.Count; day--)
|
||||||
|
{
|
||||||
|
if ((double)((daily[day] / start) - 1m) < q.ExpectedPathP5[day - 1])
|
||||||
|
{
|
||||||
|
below++;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (below >= 20)
|
||||||
|
{
|
||||||
|
list.Add(new("expected_path", $"{below} sedute di fila sotto il 5º percentile del percorso atteso"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var slippage = await SlippageAsync(account, since, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (slippage is { } bp && q.ExpectedSlippageBp > 0m && bp > 3m * q.ExpectedSlippageBp)
|
||||||
|
{
|
||||||
|
list.Add(new("slippage", $"scostamento medio {Format.Quantity(Math.Round(bp, 1))} punti base, oltre il triplo del previsto"));
|
||||||
|
}
|
||||||
|
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task LeaveLiveAsync(string strategy, string by, string reason, bool automatic, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var stage = await GetAsync(strategy, cancellationToken).ConfigureAwait(false) ?? throw new ArgumentException("Strategia sconosciuta: " + strategy, nameof(strategy));
|
||||||
|
if (!StrategyStages.IsLive(stage.Stage))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var now = clock.UtcNow;
|
||||||
|
await db.WriteAsync(async s =>
|
||||||
|
{
|
||||||
|
// The real ledger stays: its positions are closed by the strategy in exit only, and come back under normal
|
||||||
|
// management if the strategy is promoted again (SPEC 7.1).
|
||||||
|
var open = stage.LiveAccountId is { } live && (await s.QueryAsync("SELECT quantity FROM positions WHERE account_id = @a AND strategy = @s",
|
||||||
|
r => r.Money("quantity"), ("a", live), ("s", strategy)).ConfigureAwait(false)).Any(q => q > 0m);
|
||||||
|
await CarryResultsAsync(s, stage, stage.AccountId, cancellationToken).ConfigureAwait(false);
|
||||||
|
await s.ExecuteAsync("UPDATE strategy_state SET live_confirmed_at = NULL, live_confirmed_by = NULL, exit_only = @x, updated_at = @t WHERE strategy = @s", cancellationToken,
|
||||||
|
("x", open), ("t", now), ("s", strategy)).ConfigureAwait(false);
|
||||||
|
await MoveCoreAsync(s, strategy, stage.Stage, StrategyStages.Simulation, reason, by, cancellationToken).ConfigureAwait(false);
|
||||||
|
await LogChangeAsync(s, strategy, stage.Stage, StrategyStages.Simulation, by, cancellationToken).ConfigureAwait(false);
|
||||||
|
if (automatic)
|
||||||
|
{
|
||||||
|
var message = $"{StrategyNames.Label(strategy, withMarket: true)} torna in simulazione ({reason})" +
|
||||||
|
(open ? ": le posizioni reali restano in sola uscita finché non sono a zero." : ".");
|
||||||
|
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", "demotion"), ("sev", RiskSeverities.High), ("m", message),
|
||||||
|
("d", new DbJson(JsonSerializer.Serialize(new { strategy, reason }))), ("w", Worlds.Real)).ConfigureAwait(false);
|
||||||
|
await Diary.NotifyAsync(s, clock, "strategy_demoted", message, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task MoveCoreAsync(DbSession s, string strategy, string from, string to, string reason, string by, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var now = clock.UtcNow;
|
||||||
|
await s.ExecuteAsync("UPDATE strategy_state SET stage = @to, stage_since = @t, stage_reason = @r, updated_at = @t WHERE strategy = @s", cancellationToken,
|
||||||
|
("to", to), ("t", now), ("r", reason), ("s", strategy)).ConfigureAwait(false);
|
||||||
|
await s.ExecuteAsync("INSERT INTO strategy_stage_history (id, strategy, from_stage, to_stage, reason, created_at) VALUES (@id, @s, @f, @to, @r, @t)", cancellationToken,
|
||||||
|
("id", Ids.NewId(clock)), ("s", strategy), ("f", from), ("to", to), ("r", reason + " · " + by), ("t", now)).ConfigureAwait(false);
|
||||||
|
await Diary.WriteAsync(s, clock, DiaryKinds.System, "stage_changed",
|
||||||
|
$"{StrategyNames.Label(strategy, withMarket: true)}: da {StrategyStages.Label(from)} a {StrategyStages.Label(to)} ({by}).", new { strategy, from, to, reason }, cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task<int> LogChangeAsync(DbSession s, string strategy, string from, string to, string by, CancellationToken cancellationToken) =>
|
||||||
|
s.ExecuteAsync("INSERT INTO config_history (id, key, old_value, new_value, changed_by, created_at) VALUES (@id, @k, @o, @n, @by, @t)", cancellationToken,
|
||||||
|
("id", Ids.NewId(clock)), ("k", "strategy." + strategy + ".stage"), ("o", new DbJson(JsonSerializer.Serialize(from))), ("n", new DbJson(JsonSerializer.Serialize(to))),
|
||||||
|
("by", by), ("t", clock.UtcNow));
|
||||||
|
|
||||||
|
/// <summary>The results a ledger produced: everything but deposits and withdrawals, open positions at their last price.</summary>
|
||||||
|
public static async Task<decimal> LedgerResultsAsync(DbSession s, Guid account, string strategy)
|
||||||
|
{
|
||||||
|
ArgumentNullException.ThrowIfNull(s);
|
||||||
|
var rows = await s.QueryAsync("SELECT kind, amount FROM cash_ledger WHERE account_id = @a AND strategy = @s",
|
||||||
|
r => (Kind: r.Text("kind"), Amount: r.Money("amount")), ("a", account), ("s", strategy)).ConfigureAwait(false);
|
||||||
|
var positions = await s.QueryAsync("SELECT quantity, average_price, last_price FROM positions WHERE account_id = @a AND strategy = @s",
|
||||||
|
r => r.Money("quantity") * (r.MoneyOrNull("last_price") ?? r.Money("average_price")), ("a", account), ("s", strategy)).ConfigureAwait(false);
|
||||||
|
return rows.Where(r => !LedgerKinds.IsFlow(r.Kind)).Sum(r => r.Amount) + positions.Sum();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task CarryResultsAsync(DbSession s, StrategyStage stage, Guid? next, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var state = await s.FirstOrDefaultAsync("SELECT state FROM strategy_state WHERE strategy = @s", r => r.Text("state"), ("s", stage.Strategy)).ConfigureAwait(false) ?? "{}";
|
||||||
|
var node = System.Text.Json.Nodes.JsonNode.Parse(state)?.AsObject() ?? [];
|
||||||
|
var current = CarriedResults.Parse(state);
|
||||||
|
var carried = new Dictionary<Guid, decimal>(current.Carried);
|
||||||
|
var baselines = new Dictionary<Guid, decimal>(current.Baselines);
|
||||||
|
if (stage.OrdersAccount is { } leaving)
|
||||||
|
{
|
||||||
|
var results = await LedgerResultsAsync(s, leaving, stage.Strategy).ConfigureAwait(false);
|
||||||
|
var factor = stage.Stage == StrategyStages.Reduced ? 1m / StrategyStages.ReducedShare : 1m;
|
||||||
|
carried[leaving] = (carried.TryGetValue(leaving, out var c) ? c : 0m) + ((results - current.Baseline(leaving)) * factor);
|
||||||
|
baselines[leaving] = results;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (next is { } taking && taking != stage.OrdersAccount)
|
||||||
|
{
|
||||||
|
baselines[taking] = await LedgerResultsAsync(s, taking, stage.Strategy).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
System.Text.Json.Nodes.JsonObject Write(Dictionary<Guid, decimal> map) =>
|
||||||
|
new(map.Select(p => KeyValuePair.Create(p.Key.ToString("D"), (System.Text.Json.Nodes.JsonNode?)DbValues.Money(p.Value))));
|
||||||
|
node["carried"] = Write(carried);
|
||||||
|
node["baselines"] = Write(baselines);
|
||||||
|
await s.ExecuteAsync("UPDATE strategy_state SET state = @j WHERE strategy = @s", cancellationToken, ("j", new DbJson(node.ToJsonString())), ("s", stage.Strategy)).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task<List<(decimal Realized, decimal Value, decimal Fees)>> ClosedTradesAsync(string strategy, Guid? account, DateTimeOffset since, CancellationToken cancellationToken) =>
|
||||||
|
account is not { } a
|
||||||
|
? Task.FromResult(new List<(decimal, decimal, decimal)>())
|
||||||
|
: db.ReadAsync(s => s.QueryAsync("SELECT realized, bought_value, fees FROM trades WHERE account_id = @a AND strategy = @s AND status = 'closed' AND closed_at >= @f ORDER BY closed_at",
|
||||||
|
r => (r.Money("realized"), r.Money("bought_value"), r.Money("fees")), ("a", a), ("s", strategy), ("f", since)), cancellationToken);
|
||||||
|
|
||||||
|
private async Task<decimal?> OneStepAsync(string strategy, DateTimeOffset since, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var outcomes = await db.ReadAsync(s => s.QueryAsync("SELECT outcome FROM decisions WHERE strategy = @s AND stage = @st AND created_at >= @f",
|
||||||
|
r => r.Text("outcome"), ("s", strategy), ("st", DecisionStages.OneStep), ("f", since)), cancellationToken).ConfigureAwait(false);
|
||||||
|
return outcomes.Count == 0 ? null : outcomes.Count(o => o == DecisionOutcomes.Different) / (decimal)outcomes.Count;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<decimal?> SlippageAsync(Guid? account, DateTimeOffset since, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (account is not { } a)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var values = await db.ReadAsync(s => s.QueryAsync("SELECT slippage_bp FROM fills WHERE account_id = @a AND executed_at >= @f AND slippage_bp IS NOT NULL",
|
||||||
|
r => r.Money("slippage_bp"), ("a", a), ("f", since)), cancellationToken).ConfigureAwait(false);
|
||||||
|
return values.Count == 0 ? null : values.Average();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task<string?> EnvironmentOfAsync(Guid? account, CancellationToken cancellationToken) =>
|
||||||
|
account is not { } a ? Task.FromResult<string?>(null) : db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT environment FROM accounts WHERE id = @id", r => r.Text("environment"), ("id", a)), cancellationToken);
|
||||||
|
|
||||||
|
private Task<long> CriticalIncidentsAsync(DateTimeOffset since, CancellationToken cancellationToken) =>
|
||||||
|
db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM risk_events WHERE severity = @c AND occurred_at >= @f", ("c", RiskSeverities.Critical), ("f", since)), cancellationToken);
|
||||||
|
|
||||||
|
// equity_meanrev only (SPEC 12.3): the average gain at least twice the round-trip cost, and distinguishable from
|
||||||
|
// chance at 90%, checked at 30, 60, 120 and 240 closed trades, then every 120.
|
||||||
|
private static Requirement MeanrevEdge(List<(decimal Realized, decimal Value, decimal Fees)> trades, decimal roundTrip)
|
||||||
|
{
|
||||||
|
var checkpoint = Checkpoint(trades.Count);
|
||||||
|
if (checkpoint == 0)
|
||||||
|
{
|
||||||
|
return new("edge", "Guadagno medio contro il costo stimato", "servono 30 operazioni chiuse", "almeno il doppio del costo, intervallo al 90% sopra zero", false);
|
||||||
|
}
|
||||||
|
|
||||||
|
var sample = trades.Take(checkpoint).ToList();
|
||||||
|
var mean = sample.Average(t => t.Realized);
|
||||||
|
var cost = sample.Average(t => (t.Value * roundTrip) + t.Fees);
|
||||||
|
var deviation = Math.Sqrt(sample.Sum(t => Math.Pow((double)(t.Realized - mean), 2)) / Math.Max(1, sample.Count - 1));
|
||||||
|
var lower = (double)mean - (1.645 * deviation / Math.Sqrt(sample.Count));
|
||||||
|
var met = mean >= 2m * cost && lower > 0;
|
||||||
|
return new("edge", "Guadagno medio contro il costo stimato",
|
||||||
|
$"{Format.Quantity(Math.Round(mean, 2))} a operazione, costo {Format.Quantity(Math.Round(cost, 2))}, limite basso al 90% {Format.Quantity(Math.Round((decimal)lower, 2))}",
|
||||||
|
"almeno il doppio del costo, intervallo al 90% sopra zero", met);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The last checkpoint of the statistical test reached: 30, 60, 120, 240, then every 120.</summary>
|
||||||
|
public static int Checkpoint(int trades)
|
||||||
|
{
|
||||||
|
if (trades < 30)
|
||||||
|
{
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (trades < 60)
|
||||||
|
{
|
||||||
|
return 30;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (trades < 120)
|
||||||
|
{
|
||||||
|
return 60;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (trades < 240)
|
||||||
|
{
|
||||||
|
return 120;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 240 + ((trades - 240) / 120 * 120);
|
||||||
|
}
|
||||||
|
|
||||||
|
private const string Select =
|
||||||
|
"SELECT strategy, account_id, live_account_id, stage, exit_only, live_confirmed_at, stage_since, stage_reason, share, capital, qualification FROM strategy_state";
|
||||||
|
|
||||||
|
private static StrategyStage Read(DbRow r) => new(
|
||||||
|
r.Text("strategy"),
|
||||||
|
r.IdOrNull("account_id"),
|
||||||
|
r.IdOrNull("live_account_id"),
|
||||||
|
r.Text("stage"),
|
||||||
|
!r.IsNull("exit_only") && r.Bool("exit_only"),
|
||||||
|
r.MomentOrNull("live_confirmed_at"),
|
||||||
|
r.MomentOrNull("stage_since"),
|
||||||
|
r.TextOrNull("stage_reason"),
|
||||||
|
r.MoneyOrNull("share") ?? StrategyNames.Base.FirstOrDefault(b => b.Name == r.Text("strategy")).Share,
|
||||||
|
r.Money("capital"),
|
||||||
|
r.TextOrNull("qualification") is { } json ? JsonSerializer.Deserialize<Qualification>(json, Qualification.Json) : null);
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ using Anubis.Brokers;
|
|||||||
using Anubis.Core;
|
using Anubis.Core;
|
||||||
using Anubis.Data;
|
using Anubis.Data;
|
||||||
using Anubis.Db;
|
using Anubis.Db;
|
||||||
|
using Anubis.Risk;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Extensions.Logging.Abstractions;
|
using Microsoft.Extensions.Logging.Abstractions;
|
||||||
|
|
||||||
@@ -152,9 +153,11 @@ public sealed partial class TradingService : IDisposable
|
|||||||
private readonly BarStore _bars;
|
private readonly BarStore _bars;
|
||||||
private readonly ConcurrentDictionary<(string Venue, string Symbol), InstrumentSpec> _specs = new();
|
private readonly ConcurrentDictionary<(string Venue, string Symbol), InstrumentSpec> _specs = new();
|
||||||
private readonly ConcurrentDictionary<Guid, OrderManager> _managers = new();
|
private readonly ConcurrentDictionary<Guid, OrderManager> _managers = new();
|
||||||
|
private RiskLimits _limits = RiskLimits.Default;
|
||||||
|
|
||||||
public TradingService(Database db, IClock clock, EventBus bus, SecretStore secrets, MarketDataService? market, FxStore fx, TradingConsent consent, Guid installationId,
|
public TradingService(Database db, IClock clock, EventBus bus, SecretStore secrets, MarketDataService? market, FxStore fx, TradingConsent consent, Guid installationId,
|
||||||
HttpMessageHandler? handler = null, Func<IWebSocketTransport>? sockets = null, ILogger? logger = null)
|
HttpMessageHandler? handler = null, Func<IWebSocketTransport>? sockets = null, ILogger? logger = null, SettingsStore? settings = null,
|
||||||
|
Func<string, string?, CancellationToken, Task<bool>>? reauthenticate = null, string? stopFile = null)
|
||||||
{
|
{
|
||||||
_db = db ?? throw new ArgumentNullException(nameof(db));
|
_db = db ?? throw new ArgumentNullException(nameof(db));
|
||||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||||
@@ -175,8 +178,20 @@ public sealed partial class TradingService : IDisposable
|
|||||||
Capital = new Capital(db, clock, Ledger, fx);
|
Capital = new Capital(db, clock, Ledger, fx);
|
||||||
Equity = new EquityBook(db, clock, Ledger, fx);
|
Equity = new EquityBook(db, clock, Ledger, fx);
|
||||||
Quotes = new QuoteBook(clock, FetchQuoteAsync);
|
Quotes = new QuoteBook(clock, FetchQuoteAsync);
|
||||||
|
|
||||||
|
// Real money only through the procedure of SPEC 12.4: without a way to check the password it never passes.
|
||||||
|
Stages = new StageBook(db, clock, consent, reauthenticate ?? ((_, _, _) => Task.FromResult(false)));
|
||||||
|
Risk = settings is null ? null : new RiskEngine(db, clock, Ledger, Stages, settings, fx, _catalog.GetAsync, Quotes.GetAsync) { StopFile = stopFile };
|
||||||
|
_settings = settings;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private readonly SettingsStore? _settings;
|
||||||
|
|
||||||
|
public StageBook Stages { get; }
|
||||||
|
|
||||||
|
/// <summary>The risk engine every intent crosses (SPEC 9). Null only without settings, in tests of the order manager alone.</summary>
|
||||||
|
public RiskEngine? Risk { get; }
|
||||||
|
|
||||||
public string InstallationCode { get; }
|
public string InstallationCode { get; }
|
||||||
|
|
||||||
public Ledger Ledger { get; }
|
public Ledger Ledger { get; }
|
||||||
@@ -195,13 +210,27 @@ public sealed partial class TradingService : IDisposable
|
|||||||
|
|
||||||
public OrderManager? ManagerOf(Guid accountId) => _managers.GetValueOrDefault(accountId);
|
public OrderManager? ManagerOf(Guid accountId) => _managers.GetValueOrDefault(accountId);
|
||||||
|
|
||||||
/// <summary>Accounts, brokers and order managers; then the simulator catches up, keys are checked and every account reconciled.</summary>
|
/// <summary>
|
||||||
public async Task StartAsync(CancellationToken cancellationToken)
|
/// Accounts, strategies and their backtest outcomes, in the database only: the host runs it before it is ready, so no
|
||||||
|
/// page ever shows a strategy without its outcome. Repeating it changes nothing.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<IReadOnlyList<AccountContext>> PrepareAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var alpaca = await AlpacaKeysAsync(cancellationToken).ConfigureAwait(false);
|
var alpaca = await AlpacaKeysAsync(cancellationToken).ConfigureAwait(false);
|
||||||
var okx = await OkxKeysAsync(cancellationToken).ConfigureAwait(false);
|
var okx = await OkxKeysAsync(cancellationToken).ConfigureAwait(false);
|
||||||
var accounts = await AccountSetup.EnsureAsync(_db, _clock, alpaca is not null, okx is not null, cancellationToken).ConfigureAwait(false);
|
var accounts = await AccountSetup.EnsureAsync(_db, _clock, alpaca is not null, okx is not null, cancellationToken).ConfigureAwait(false);
|
||||||
|
await LoadOutcomesAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
return accounts;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Accounts, brokers and order managers; then the simulator catches up, keys are checked and every account reconciled.</summary>
|
||||||
|
public async Task StartAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var accounts = await PrepareAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
var alpaca = await AlpacaKeysAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
var okx = await OkxKeysAsync(cancellationToken).ConfigureAwait(false);
|
||||||
await RefreshSpecsAsync(cancellationToken).ConfigureAwait(false);
|
await RefreshSpecsAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
await RefreshLimitsAsync(cancellationToken).ConfigureAwait(false);
|
||||||
foreach (var account in accounts)
|
foreach (var account in accounts)
|
||||||
{
|
{
|
||||||
var broker = Build(account, alpaca, okx);
|
var broker = Build(account, alpaca, okx);
|
||||||
@@ -217,6 +246,9 @@ public sealed partial class TradingService : IDisposable
|
|||||||
MarketOpen = MarketOpenAsync,
|
MarketOpen = MarketOpenAsync,
|
||||||
PendingSplit = (instrument, ct) => PendingSplitAsync(account.AccountId, instrument, ct),
|
PendingSplit = (instrument, ct) => PendingSplitAsync(account.AccountId, instrument, ct),
|
||||||
AfterFills = async ct => await Equity.TakeAsync(ct).ConfigureAwait(false),
|
AfterFills = async ct => await Equity.TakeAsync(ct).ConfigureAwait(false),
|
||||||
|
Gate = Risk is null ? null : Risk.GateAsync,
|
||||||
|
LivePermit = Stages.LiveRefusalAsync,
|
||||||
|
PurchasePriceCheck = (limit, quote) => RiskRules.TechnicalRefusal(_clock.UtcNow, quote.At, quote.Mid, limit, null, _limits),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -241,13 +273,55 @@ public sealed partial class TradingService : IDisposable
|
|||||||
await GuardAsync("patrimonio", () => PhotographAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
await GuardAsync("patrimonio", () => PhotographAsync(cancellationToken), cancellationToken).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The backtest outcomes built into the program (docs/backtests): at the first start a base strategy that passed
|
||||||
|
/// moves to simulation, one that did not stays in observation with the reason (SPEC 12.3).
|
||||||
|
/// </summary>
|
||||||
|
public async Task LoadOutcomesAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
foreach (var (strategy, _, _) in StrategyNames.Base)
|
||||||
|
{
|
||||||
|
if (Backtest.BacktestOutcomes.Find(strategy) is { } outcome)
|
||||||
|
{
|
||||||
|
await Stages.ApplyQualificationAsync(strategy, outcome, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public IReadOnlyList<ScheduledJob> Jobs() =>
|
public IReadOnlyList<ScheduledJob> Jobs() =>
|
||||||
[
|
[
|
||||||
new ScheduledJob("riconciliazione", "Riconciliazione dei conti", Schedule.Every(TimeSpan.FromMinutes(5)), ReconcileAllAsync),
|
new ScheduledJob("riconciliazione", "Riconciliazione dei conti", Schedule.Every(TimeSpan.FromMinutes(5)), ReconcileAllAsync),
|
||||||
new ScheduledJob("patrimonio", "Fotografia del patrimonio", Schedule.Every(TimeSpan.FromMinutes(5)), PhotographAsync),
|
new ScheduledJob("patrimonio", "Fotografia del patrimonio", Schedule.Every(TimeSpan.FromMinutes(5)), PhotographAsync),
|
||||||
new ScheduledJob("azioni_societarie", "Dividendi e frazionamenti nei registri", Schedule.Every(TimeSpan.FromHours(1)), CorporateActionsAsync),
|
new ScheduledJob("azioni_societarie", "Dividendi e frazionamenti nei registri", Schedule.Every(TimeSpan.FromHours(1)), CorporateActionsAsync),
|
||||||
|
new ScheduledJob("rischio", "Controllo del rischio e dell'interruttore", Schedule.Every(TimeSpan.FromMinutes(1)), CheckRiskAsync),
|
||||||
|
new ScheduledJob("stadi", "Retrocessioni e sola uscita delle strategie", Schedule.Every(TimeSpan.FromHours(1)), CheckStagesAsync),
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/// <summary>The risk check of every minute (SPEC 9.2, 9.3): limits of each world, orders per minute, the STOP file.</summary>
|
||||||
|
public async Task CheckRiskAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
await RefreshLimitsAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
if (Risk is not null)
|
||||||
|
{
|
||||||
|
await Risk.CheckAsync(Managers, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Automatic demotions (SPEC 12.3) and the end of exit only once real positions are at zero.</summary>
|
||||||
|
public async Task CheckStagesAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
await Stages.CheckDemotionsAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
await Stages.ReleaseExitOnlyAsync(Ledger, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task RefreshLimitsAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (_settings is not null)
|
||||||
|
{
|
||||||
|
_limits = await RiskSettings.LoadAsync(_settings, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>The working loop: quotes from the stream, order updates from the brokers, a turn of every account every few seconds.</summary>
|
/// <summary>The working loop: quotes from the stream, order updates from the brokers, a turn of every account every few seconds.</summary>
|
||||||
public async Task RunAsync(CancellationToken cancellationToken)
|
public async Task RunAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ public sealed class AccountsScreenTests
|
|||||||
[TestCategory(Category.Integration)]
|
[TestCategory(Category.Integration)]
|
||||||
public async Task TheDemoShowsTheFiguresOfTheMockup()
|
public async Task TheDemoShowsTheFiguresOfTheMockup()
|
||||||
{
|
{
|
||||||
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
|
var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
|
||||||
var demoRoot = server.Host.Config.Data.Root;
|
var demoRoot = server.Host.Config.Data.Root;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -58,6 +58,8 @@ public sealed class AccountsScreenTests
|
|||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
|
// The server first: on Windows a database still open cannot be deleted.
|
||||||
|
await server.DisposeAsync();
|
||||||
TempFolder.Delete(demoRoot);
|
TempFolder.Delete(demoRoot);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ public sealed class LaboratoryScreenTests
|
|||||||
"Esito del protocollo", "Risultato netto con costi doppi", "Deflated Sharpe Ratio", "Probabilità di sovra-adattamento (PBO)",
|
"Esito del protocollo", "Risultato netto con costi doppi", "Deflated Sharpe Ratio", "Probabilità di sovra-adattamento (PBO)",
|
||||||
"Risultato della variante scelta", "Comprare e tenere", "Risultato per anno", "Sensibilità ai costi", "Finestre che avanzano",
|
"Risultato della variante scelta", "Comprare e tenere", "Risultato per anno", "Sensibilità ai costi", "Finestre che avanzano",
|
||||||
"K-fold purgato combinatorio", "Nessuno sguardo in avanti", "nessuna è cambiata", "Tutte le varianti", "Cosa questo test non considera",
|
"K-fold purgato combinatorio", "Nessuno sguardo in avanti", "nessuna è cambiata", "Tutte le varianti", "Cosa questo test non considera",
|
||||||
"Fase 5", "Impronta dei dati", "Vedi i numeri in una tabella",
|
"esempio: correttivi e limiti di rischio non si applicano", "Impronta dei dati", "Vedi i numeri in una tabella",
|
||||||
})
|
})
|
||||||
{
|
{
|
||||||
StringAssert.Contains(report, part, $"Missing \"{part}\" in the report.");
|
StringAssert.Contains(report, part, $"Missing \"{part}\" in the report.");
|
||||||
|
|||||||
@@ -68,7 +68,7 @@ public sealed class LaboratoryTests
|
|||||||
Assert.IsNotNull(report.Combinatorial);
|
Assert.IsNotNull(report.Combinatorial);
|
||||||
Assert.IsNotNull(report.Overfitting);
|
Assert.IsNotNull(report.Overfitting);
|
||||||
Assert.IsTrue(report.Curve.Count is > 100 and <= TrialRunner.MaxCurvePoints + 1);
|
Assert.IsTrue(report.Curve.Count is > 100 and <= TrialRunner.MaxCurvePoints + 1);
|
||||||
Assert.IsTrue(report.Limitations.Any(l => l.Contains("Fase 5", StringComparison.Ordinal)));
|
Assert.IsTrue(report.Limitations.Any(l => l.Contains("Strategia d'esempio", StringComparison.Ordinal)));
|
||||||
|
|
||||||
// A second trial of the same strategy deflates for the variants of both.
|
// A second trial of the same strategy deflates for the variants of both.
|
||||||
var second = await lab.PlanAsync(Request() with { Grid = new Dictionary<string, IReadOnlyList<decimal>> { ["fast"] = [10m], ["slow"] = [30m] } },
|
var second = await lab.PlanAsync(Request() with { Grid = new Dictionary<string, IReadOnlyList<decimal>> { ["fast"] = [10m], ["slow"] = [30m] } },
|
||||||
@@ -209,7 +209,8 @@ public sealed class LaboratoryTests
|
|||||||
var data = await Laboratory.LoadAsync(null!, SystemClock.Instance, root,
|
var data = await Laboratory.LoadAsync(null!, SystemClock.Instance, root,
|
||||||
new TrialData(TrialSources.Research, Venues.Binance, ["ETHUSDT"], From.AddDays(10), From.AddDays(29)), CancellationToken.None).ConfigureAwait(false);
|
new TrialData(TrialSources.Research, Venues.Binance, ["ETHUSDT"], From.AddDays(10), From.AddDays(29)), CancellationToken.None).ConfigureAwait(false);
|
||||||
Assert.AreEqual("USDT", data.Currency);
|
Assert.AreEqual("USDT", data.Currency);
|
||||||
Assert.HasCount(20, data.Sessions);
|
Assert.HasCount(30, data.Sessions, "the days before the start are read too, for the indicators");
|
||||||
|
Assert.AreEqual(20, data.Sessions.Count(d => d >= From.AddDays(10)), "the trial itself covers its 20 days");
|
||||||
Assert.AreEqual("ETH", data["ETHUSDT"]!.Spec.BaseCurrency);
|
Assert.AreEqual("ETH", data["ETHUSDT"]!.Spec.BaseCurrency);
|
||||||
Assert.IsTrue(data.IsCrypto);
|
Assert.IsTrue(data.IsCrypto);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,218 @@
|
|||||||
|
using Anubis.Backtest;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Platform;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The honest backtests of the base strategies (issue #44; SPEC 8.1, 12.2, 12.3): the Binance history in euro, the
|
||||||
|
/// protocol on both universes of crypto_trend, the expected path, the report and the outcome files read at the first
|
||||||
|
/// start.
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class ProtocolTests
|
||||||
|
{
|
||||||
|
private static readonly CancellationToken _none = CancellationToken.None;
|
||||||
|
|
||||||
|
private static ResearchBar Bar(DateOnly day, decimal close) =>
|
||||||
|
new(new DateTimeOffset(day.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), close, close * 1.01m, close * 0.99m, close, 100m) { QuoteVolume = close * 100m };
|
||||||
|
|
||||||
|
private static FxRate Usd(DateOnly day, decimal rate) => new("EUR", "USD", day, rate, "ecb");
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void UsdtPricesBecomeEurosWithTheLastRateFixedBeforeTheBarOpens()
|
||||||
|
{
|
||||||
|
var thursday = new DateOnly(2024, 2, 29);
|
||||||
|
var friday = thursday.AddDays(1);
|
||||||
|
var bars = new[] { Bar(friday, 110m), Bar(friday.AddDays(1), 120m), Bar(friday.AddDays(3), 100m), Bar(friday.AddDays(4), 125m) };
|
||||||
|
var rates = new[] { Usd(thursday, 1.10m), Usd(friday, 1.20m), Usd(friday.AddDays(3), 1.25m) };
|
||||||
|
|
||||||
|
var euro = EuroHistory.Convert(bars, rates);
|
||||||
|
|
||||||
|
Assert.HasCount(4, euro);
|
||||||
|
Assert.AreEqual(100m, euro[0].Close, "Friday's bar opens before Friday's rate is fixed: Thursday's");
|
||||||
|
Assert.AreEqual(100m, euro[1].Close); // Saturday: Friday's rate.
|
||||||
|
Assert.AreEqual(83.333333333333m, euro[2].Close); // Monday: still Friday's, Monday's comes in the afternoon.
|
||||||
|
Assert.AreEqual(100m, euro[3].Close); // Tuesday: Monday's.
|
||||||
|
Assert.AreEqual(100m, euro[0].Volume, "the volume is in coins: it does not change");
|
||||||
|
Assert.AreEqual(10_000m, euro[0].QuoteVolume);
|
||||||
|
Assert.AreEqual("BTCEUR", EuroHistory.SymbolOf("BTCUSDT"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void ABarWithoutARecentRateIsDropped()
|
||||||
|
{
|
||||||
|
var day = new DateOnly(2024, 3, 1);
|
||||||
|
var bars = Enumerable.Range(-1, EuroHistory.MaxRateAgeDays + 3).Select(i => Bar(day.AddDays(i), 1m)).ToList();
|
||||||
|
|
||||||
|
var euro = EuroHistory.Convert(bars, [Usd(day, 1m)]);
|
||||||
|
|
||||||
|
Assert.HasCount(EuroHistory.MaxRateAgeDays, euro, "up to the first rate and after a week without rates there is no price in euro");
|
||||||
|
Assert.AreEqual(day.AddDays(1), DateOnly.FromDateTime(euro[0].OpensAt.UtcDateTime));
|
||||||
|
Assert.AreEqual(day.AddDays(EuroHistory.MaxRateAgeDays), DateOnly.FromDateTime(euro[^1].OpensAt.UtcDateTime));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AHoleOfMoreThanAWeekEndsTheSeriesBecauseWhatFollowsIsAnotherCoin()
|
||||||
|
{
|
||||||
|
var day = new DateOnly(2022, 5, 10);
|
||||||
|
var bars = new[] { Bar(day, 1m), Bar(day.AddDays(1), 0.0001m), Bar(day.AddDays(1 + EuroHistory.MaxGapDays + 1), 5m), Bar(day.AddDays(2 + EuroHistory.MaxGapDays + 1), 6m) };
|
||||||
|
var rates = Enumerable.Range(-1, 21).Select(i => Usd(day.AddDays(i), 1m)).ToList();
|
||||||
|
|
||||||
|
var euro = EuroHistory.Convert(bars, rates);
|
||||||
|
|
||||||
|
Assert.HasCount(2, euro, "the relaunch under the same ticker is not the coin that collapsed");
|
||||||
|
Assert.AreEqual(0.0001m, euro[^1].Close);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TheExpectedPathIsTheCompoundedPercentileAndRepeatsWithTheSameSeed()
|
||||||
|
{
|
||||||
|
var steady = PathBootstrap.Percentile([0.01, 0.01, 0.01], 3, 0.05, 50, 5, 1);
|
||||||
|
Assert.AreEqual(0.01, steady[0], 1e-12);
|
||||||
|
Assert.AreEqual(0.030301, steady[2], 1e-12);
|
||||||
|
|
||||||
|
var random = new Random(7);
|
||||||
|
var returns = Enumerable.Range(0, 500).Select(_ => (random.NextDouble() - 0.48) * 0.06).ToArray();
|
||||||
|
var p5 = PathBootstrap.Percentile(returns, 100, 0.05, 500, 20, 3);
|
||||||
|
var median = PathBootstrap.Percentile(returns, 100, 0.50, 500, 20, 3);
|
||||||
|
CollectionAssert.AreEqual(p5.ToList(), PathBootstrap.Percentile(returns, 100, 0.05, 500, 20, 3).ToList());
|
||||||
|
Assert.IsTrue(p5.Zip(median).All(x => x.First <= x.Second), "the 5th percentile is never above the median");
|
||||||
|
Assert.IsLessThan(p5[9], p5[99], "the bad tail widens with time");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task TheProtocolRunsBothUniversesAndWritesTheReportWhateverTheOutcome()
|
||||||
|
{
|
||||||
|
var folder = TempFolder.Create("protocol");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var store = new ResearchStore(folder);
|
||||||
|
var random = new Random(11);
|
||||||
|
var start = new DateOnly(2017, 8, 1);
|
||||||
|
var end = new DateOnly(2020, 12, 31);
|
||||||
|
foreach (var coin in new[] { "BTC", "ETH", "SOL", "XRP", "LTC" })
|
||||||
|
{
|
||||||
|
var price = 100m;
|
||||||
|
var bars = new List<ResearchBar>();
|
||||||
|
for (var day = start; day <= end; day = day.AddDays(1))
|
||||||
|
{
|
||||||
|
price *= 1m + (decimal)((random.NextDouble() - 0.49) * 0.08);
|
||||||
|
bars.Add(Bar(day, Math.Round(price, 6)) with { Volume = 1_000_000m });
|
||||||
|
}
|
||||||
|
|
||||||
|
await store.WriteAsync(Venues.Binance, coin + "USDT", Timeframes.Day, bars, _none);
|
||||||
|
}
|
||||||
|
|
||||||
|
var rates = new List<FxRate>();
|
||||||
|
for (var day = start; day <= end; day = day.AddDays(1))
|
||||||
|
{
|
||||||
|
if (day.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday))
|
||||||
|
{
|
||||||
|
rates.Add(Usd(day, 1.15m));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var converted = await EuroHistory.ConvertAllAsync(store, rates, _none);
|
||||||
|
Assert.HasCount(5, converted);
|
||||||
|
|
||||||
|
var outcome = await CryptoTrendProtocol.RunAsync(folder, end, new DateTimeOffset(2021, 1, 2, 0, 0, 0, TimeSpan.Zero), null, _none);
|
||||||
|
|
||||||
|
Assert.HasCount(2, outcome.Runs);
|
||||||
|
Assert.HasCount(5, outcome.Runs[0].Report.Instruments);
|
||||||
|
CollectionAssert.AreEqual(CryptoTrendProtocol.Narrow.ToList(), outcome.Runs[1].Report.Instruments.Select(i => i.Symbol).ToList());
|
||||||
|
Assert.AreEqual("EUR", outcome.Runs[0].Report.Currency);
|
||||||
|
Assert.AreEqual(outcome.Runs[0].Report.Variants.Count + outcome.Runs[1].Report.Variants.Count, outcome.Runs[1].Report.TrialsCounted,
|
||||||
|
"the second universe counts the variants of the first as tries");
|
||||||
|
Assert.IsTrue(outcome.Runs.All(r => r.Report.LookAhead.Passed), "no decision changes when later data is added");
|
||||||
|
|
||||||
|
var q = outcome.Qualification;
|
||||||
|
Assert.AreEqual(outcome.Runs.All(r => r.Report.Passed), q.Passed);
|
||||||
|
Assert.AreEqual(CryptoTrendProtocol.ReportPath, q.Report);
|
||||||
|
Assert.HasCount(CryptoTrendProtocol.PathDays, q.ExpectedPathP5);
|
||||||
|
Assert.AreEqual(Math.Round((decimal)outcome.Runs[0].Report.Metrics.MaxDrawdown, 4), q.MaxDrawdown);
|
||||||
|
Assert.IsTrue(q.ExpectedSlippageBp is >= 5m and <= 15m);
|
||||||
|
Assert.AreEqual(2m * (0.002m + (q.ExpectedSlippageBp / 10_000m)), q.RoundTripCost);
|
||||||
|
if (!q.Passed)
|
||||||
|
{
|
||||||
|
StringAssert.Contains(q.Verdict, "Resta in osservazione");
|
||||||
|
}
|
||||||
|
|
||||||
|
var markdown = ProtocolReport.Markdown(outcome, "crypto_trend", ["dati di prova"], "anubis backtest base");
|
||||||
|
foreach (var part in new[] { "# Backtest di `crypto_trend`", "## Universo ampio", "## BTC, ETH e SOL", "Comprare e tenere", "×2", "×3", "**Per anno**",
|
||||||
|
"Deflated Sharpe Ratio", "convertiti in euro con il cambio BCE", "dati di prova" })
|
||||||
|
{
|
||||||
|
StringAssert.Contains(markdown, part);
|
||||||
|
}
|
||||||
|
|
||||||
|
var json = BacktestOutcomes.ToJson(q);
|
||||||
|
Assert.AreEqual(q.Verdict, System.Text.Json.JsonSerializer.Deserialize<Qualification>(json, Qualification.Json)!.Verdict);
|
||||||
|
StringAssert.Contains(json, "\"expected_path_p5\"");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
TempFolder.Delete(folder);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void AFailedCheckIsDescribedInPlainItalian()
|
||||||
|
{
|
||||||
|
var check = new ReportCheck(ReportCheckKeys.Drawdown, "Calo massimo", 0.382, "≤", 0.25, "percent", false);
|
||||||
|
|
||||||
|
Assert.AreEqual("calo massimo 38,2%, serve ≤ 25%", CryptoTrendProtocol.Describe(check, System.Globalization.CultureInfo.GetCultureInfo("it-IT")));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void EveryBaseStrategyHasItsOutcomeFileBuiltIn()
|
||||||
|
{
|
||||||
|
foreach (var (strategy, _, _) in StrategyNames.Base)
|
||||||
|
{
|
||||||
|
var outcome = BacktestOutcomes.Find(strategy);
|
||||||
|
Assert.IsNotNull(outcome, strategy);
|
||||||
|
Assert.AreEqual("docs/backtests/" + strategy + ".md", outcome.Report);
|
||||||
|
Assert.IsTrue(File.Exists(Path.Combine(RepositoryRoot(), outcome.Report)), "the report of " + strategy + " is in the repository");
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var strategy in new[] { StrategyNames.EquityMomentum, StrategyNames.EquityMeanrev })
|
||||||
|
{
|
||||||
|
var outcome = BacktestOutcomes.Find(strategy)!;
|
||||||
|
Assert.IsFalse(outcome.Passed, "without the Alpaca history the stock strategies cannot pass");
|
||||||
|
StringAssert.Contains(outcome.Verdict, "chiavi Alpaca");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public async Task AtTheFirstStartTheStockStrategiesWaitInObservationAndCryptoFollowsItsOutcome()
|
||||||
|
{
|
||||||
|
await using var rig = await TradingRig.CreateAsync();
|
||||||
|
await AccountSetup.EnsureAsync(rig.Db, rig.Clock, alpacaDemo: false, okxDemo: false, _none);
|
||||||
|
var stages = new StageBook(rig.Db, rig.Clock, TradingConsent.None, (_, _, _) => Task.FromResult(false));
|
||||||
|
foreach (var (strategy, _, _) in StrategyNames.Base)
|
||||||
|
{
|
||||||
|
await stages.ApplyQualificationAsync(strategy, BacktestOutcomes.Find(strategy)!, _none);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var strategy in new[] { StrategyNames.EquityMomentum, StrategyNames.EquityMeanrev })
|
||||||
|
{
|
||||||
|
var stage = await stages.GetAsync(strategy, _none);
|
||||||
|
Assert.AreEqual(StrategyStages.Observation, stage!.Stage);
|
||||||
|
StringAssert.Contains(stage.Qualification!.Verdict, "chiavi Alpaca");
|
||||||
|
}
|
||||||
|
|
||||||
|
var crypto = (await stages.GetAsync(StrategyNames.CryptoTrend, _none))!;
|
||||||
|
Assert.AreEqual(BacktestOutcomes.Find(StrategyNames.CryptoTrend)!.Passed ? StrategyStages.Simulation : StrategyStages.Observation, crypto.Stage);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string RepositoryRoot()
|
||||||
|
{
|
||||||
|
var folder = new DirectoryInfo(AppContext.BaseDirectory);
|
||||||
|
while (folder is not null && !File.Exists(Path.Combine(folder.FullName, "Anubis.slnx")))
|
||||||
|
{
|
||||||
|
folder = folder.Parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
return folder?.FullName ?? throw new InvalidOperationException("Repository root not found");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,664 @@
|
|||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Db;
|
||||||
|
using Anubis.Platform;
|
||||||
|
using Anubis.Risk;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The risk engine at work on the database (issues #42, #43; SPEC 9, 12.3, 12.4): the gate of every order, the switch
|
||||||
|
/// of each world, the STOP file, the orders per minute, the day-trade guard, and the only way to real money, tested
|
||||||
|
/// against a fake real account (a simulator that says "live").
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class RiskEngineTests
|
||||||
|
{
|
||||||
|
private static readonly CancellationToken _none = CancellationToken.None;
|
||||||
|
private static readonly TimeSpan _minute = TimeSpan.FromSeconds(60);
|
||||||
|
private const string Password = "password-giusta";
|
||||||
|
|
||||||
|
private sealed class Setup : IAsyncDisposable
|
||||||
|
{
|
||||||
|
public required TradingRig Rig { get; init; }
|
||||||
|
|
||||||
|
public required SettingsStore Settings { get; init; }
|
||||||
|
|
||||||
|
public required StageBook Stages { get; init; }
|
||||||
|
|
||||||
|
public required RiskEngine Risk { get; init; }
|
||||||
|
|
||||||
|
public required AccountContext Account { get; init; }
|
||||||
|
|
||||||
|
public required Instrument Btc { get; init; }
|
||||||
|
|
||||||
|
public List<IDisposable> Owned { get; } = [];
|
||||||
|
|
||||||
|
public string? Folder { get; init; }
|
||||||
|
|
||||||
|
public async ValueTask DisposeAsync()
|
||||||
|
{
|
||||||
|
foreach (var owned in Owned)
|
||||||
|
{
|
||||||
|
owned.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Folder is not null)
|
||||||
|
{
|
||||||
|
TempFolder.Delete(Folder);
|
||||||
|
}
|
||||||
|
|
||||||
|
await Rig.DisposeAsync().ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A real-money consent as the startup configuration would give it: only for the fake real account of these tests.</summary>
|
||||||
|
private static TradingConsent Consent() => TradingConsent.From(DockerPlatform.Load(new Dictionary<string, string?>
|
||||||
|
{
|
||||||
|
["ANUBIS_DB_ENGINE"] = "sqlite",
|
||||||
|
["ANUBIS_SECRET_KEY"] = new string('k', 40),
|
||||||
|
["ANUBIS_ADMIN_PASSWORD"] = "initial-pass-1",
|
||||||
|
["ANUBIS_ALLOW_LIVE"] = "1",
|
||||||
|
}));
|
||||||
|
|
||||||
|
/// <summary>crypto_trend in simulation on the OKX simulator with 10 000 €, BTC at 60 000.</summary>
|
||||||
|
private static async Task<Setup> CreateAsync(TradingConsent? consent = null, bool stopFile = false)
|
||||||
|
{
|
||||||
|
var rig = await TradingRig.CreateAsync().ConfigureAwait(false);
|
||||||
|
var settings = new SettingsStore(rig.Db, rig.Clock, new EventBus());
|
||||||
|
var stages = new StageBook(rig.Db, rig.Clock, consent ?? TradingConsent.None, (password, _, _) => Task.FromResult(password == Password));
|
||||||
|
var folder = stopFile ? TempFolder.Create("stop") : null;
|
||||||
|
var risk = new RiskEngine(rig.Db, rig.Clock, rig.Ledger, stages, settings, new FxStore(rig.Db, rig.Clock), rig.FindAsync, rig.QuoteAsync)
|
||||||
|
{
|
||||||
|
StopFile = folder is null ? null : Path.Combine(folder, "STOP"),
|
||||||
|
};
|
||||||
|
var account = await rig.AccountAsync(Venues.Okx, TradingEnvironments.Simulation).ConfigureAwait(false);
|
||||||
|
var btc = await rig.InstrumentAsync(TradingRig.Btc).ConfigureAwait(false);
|
||||||
|
rig.Quote(btc.Symbol, 60_000m, 60_010m);
|
||||||
|
await rig.Ledger.RecordCapitalAsync(account.AccountId, StrategyNames.CryptoTrend, 10_000m, "EUR", "test", _none).ConfigureAwait(false);
|
||||||
|
await StageRowAsync(rig, StrategyNames.CryptoTrend, account.AccountId, StrategyStages.Simulation, rig.Clock.UtcNow).ConfigureAwait(false);
|
||||||
|
return new Setup { Rig = rig, Settings = settings, Stages = stages, Risk = risk, Account = account, Btc = btc, Folder = folder };
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Task<int> StageRowAsync(TradingRig rig, string strategy, Guid account, string stage, DateTimeOffset since) =>
|
||||||
|
rig.Db.WriteAsync(s => s.ExecuteAsync(
|
||||||
|
"INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at, share, stage_since) VALUES (@id, @s, @a, @st, 0, @j, @t, @t, 1, @since)",
|
||||||
|
_none, ("id", Ids.NewId(rig.Clock)), ("s", strategy), ("a", account), ("st", stage), ("j", new DbJson("{}")), ("t", rig.Clock.UtcNow), ("since", since)), _none);
|
||||||
|
|
||||||
|
private static TradeIntent Buy(Setup s, decimal quantity, string strategy = StrategyNames.CryptoTrend, Instrument? instrument = null) =>
|
||||||
|
new((instrument ?? s.Btc).Id, strategy, OrderSide.Buy, quantity, OrderPurpose.Entry, Ids.NewId(s.Rig.Clock)) { StopLevel = 57_000m };
|
||||||
|
|
||||||
|
private static TradeIntent Sell(Setup s, decimal quantity, string strategy = StrategyNames.CryptoTrend, OrderPurpose purpose = OrderPurpose.Exit, Instrument? instrument = null) =>
|
||||||
|
new((instrument ?? s.Btc).Id, strategy, OrderSide.Sell, quantity, purpose, Ids.NewId(s.Rig.Clock));
|
||||||
|
|
||||||
|
private static Task<FillOutcome> HoldAsync(Setup s, AccountContext account, decimal quantity, string strategy = StrategyNames.CryptoTrend, Instrument? instrument = null) =>
|
||||||
|
s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(account, instrument ?? s.Btc, strategy, OrderSide.Buy, quantity, 60_000m), _none);
|
||||||
|
|
||||||
|
private static Task<int> SnapshotAsync(TradingRig rig, string world, DateTimeOffset at, decimal index) =>
|
||||||
|
rig.Db.WriteAsync(s => s.ExecuteAsync(
|
||||||
|
"INSERT INTO equity_snapshots (id, taken_at, scope, account_id, strategy, equity, cash, invested, drawdown_pct, created_at, world, currency, flows, twr_index, peak_index) " +
|
||||||
|
"VALUES (@id, @t, 'total', NULL, NULL, @e, @e, 0, 0, @t, @w, 'EUR', 10000, @x, @x)", _none,
|
||||||
|
("id", Ids.NewId(rig.Clock)), ("t", at), ("e", 10_000m * index), ("w", world), ("x", index)), _none);
|
||||||
|
|
||||||
|
private static Task<IReadOnlyList<string>> EventsAsync(TradingRig rig, string kind) =>
|
||||||
|
rig.QueryAsync("SELECT severity FROM risk_events WHERE kind = @k", r => r.Text("severity"), ("k", kind));
|
||||||
|
|
||||||
|
// ---- The gate: stop, pause, ownership, sizes ----
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task PauseStopsEntriesAndStopStopsEverythingButProtection()
|
||||||
|
{
|
||||||
|
await using var s = await CreateAsync();
|
||||||
|
await HoldAsync(s, s.Account, 0.01m);
|
||||||
|
Assert.AreEqual(0.01m, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Quantity);
|
||||||
|
|
||||||
|
await s.Settings.SetAsync(SettingsStore.BotState.Key, "paused", "test");
|
||||||
|
Assert.AreEqual(RiskReasons.BotPaused, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal);
|
||||||
|
Assert.IsNull((await s.Risk.GateAsync(Sell(s, 0.01m), s.Account, _none)).Refusal, "exits go on in pause");
|
||||||
|
|
||||||
|
await s.Settings.SetAsync(SettingsStore.BotState.Key, "stopped", "test");
|
||||||
|
Assert.AreEqual(RiskReasons.BotStopped, (await s.Risk.GateAsync(Sell(s, 0.01m), s.Account, _none)).Refusal, "no sales on the strategy's initiative");
|
||||||
|
Assert.IsNull((await s.Risk.GateAsync(Sell(s, 0.01m, purpose: OrderPurpose.Protective), s.Account, _none)).Refusal, "protection always passes");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task NoShortSalesAndNothingThatTheStrategyDidNotBuy()
|
||||||
|
{
|
||||||
|
await using var s = await CreateAsync();
|
||||||
|
Assert.AreEqual(RiskReasons.NotOwned, (await s.Risk.GateAsync(Sell(s, 0.01m), s.Account, _none)).Refusal, "a position the bot did not open is never touched");
|
||||||
|
|
||||||
|
await HoldAsync(s, s.Account, 0.01m);
|
||||||
|
Assert.AreEqual(RiskReasons.OwnedByOther, (await s.Risk.GateAsync(Sell(s, 0.01m, StrategyNames.EquityMomentum), s.Account, _none)).Refusal);
|
||||||
|
var more = await s.Risk.GateAsync(Sell(s, 0.05m), s.Account, _none);
|
||||||
|
Assert.AreEqual(0.01m, more.Quantity);
|
||||||
|
CollectionAssert.Contains(more.Reasons.ToList(), RiskReasons.NoShortSelling);
|
||||||
|
Assert.AreEqual(RiskReasons.NoShortSelling, (await s.Risk.GateAsync(Buy(s, 0.01m) with { Purpose = OrderPurpose.Exit }, s.Account, _none)).Refusal);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task APurchaseIsShrunkAndTheDecisionRecordsWhy()
|
||||||
|
{
|
||||||
|
await using var s = await CreateAsync();
|
||||||
|
var intent = Buy(s, 0.5m);
|
||||||
|
var result = await s.Risk.GateAsync(intent, s.Account, _none);
|
||||||
|
|
||||||
|
// 0.5 BTC is three times the equity; 20% of it at 60 010 is 0.0333 BTC; the risk to the stop, 1% of 10 000 over 3 010, a little less.
|
||||||
|
Assert.IsNull(result.Refusal);
|
||||||
|
Assert.AreEqual(Math.Round(100m / 3_010m, 8), Math.Round(result.Quantity, 8));
|
||||||
|
CollectionAssert.AreEqual(new[] { RiskReasons.InvestedLimit, RiskReasons.PositionLimit, RiskReasons.TradeRiskLimit }, result.Reasons.ToList(), string.Join(",", result.Reasons));
|
||||||
|
var row = (await new DecisionLog(s.Rig.Db, s.Rig.Clock).OfAsync(intent.DecisionId, _none)).Single();
|
||||||
|
Assert.AreEqual(DecisionStages.Risk, row.Stage);
|
||||||
|
Assert.AreEqual(DecisionOutcomes.Reduced, row.Outcome);
|
||||||
|
CollectionAssert.Contains(row.Reasons.ToList(), RiskReasons.TradeRiskLimit);
|
||||||
|
Assert.IsTrue(row.Data!.ContainsKey("reference"));
|
||||||
|
|
||||||
|
// No leverage: with the rest of the bot ten times larger the limits allow more, the strategy's own cash does not.
|
||||||
|
// The purchase counts at the highest price its limit may chase to.
|
||||||
|
await s.Rig.Ledger.RecordCapitalAsync(s.Account.AccountId, "sma_cross", 90_000m, "EUR", "test", _none);
|
||||||
|
var poor = await s.Risk.GateAsync(Buy(s, 0.5m), s.Account, _none);
|
||||||
|
Assert.AreEqual(Math.Round(10_000m / (60_010m * (1m + RiskLimits.Default.MaxPriceGap)), 8), Math.Round(poor.Quantity, 8));
|
||||||
|
Assert.AreEqual(RiskReasons.NoLeverage, poor.Reasons[^1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task OldPricesStopEntriesButNotExits()
|
||||||
|
{
|
||||||
|
await using var s = await CreateAsync();
|
||||||
|
await HoldAsync(s, s.Account, 0.01m);
|
||||||
|
s.Rig.Clock.Advance(TimeSpan.FromSeconds(61));
|
||||||
|
Assert.AreEqual(RiskReasons.StalePrice, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal);
|
||||||
|
Assert.IsNull((await s.Risk.GateAsync(Sell(s, 0.01m), s.Account, _none)).Refusal);
|
||||||
|
|
||||||
|
s.Rig.Refresh();
|
||||||
|
var skewed = new RiskEngine(s.Rig.Db, s.Rig.Clock, s.Rig.Ledger, s.Stages, s.Settings, new FxStore(s.Rig.Db, s.Rig.Clock), s.Rig.FindAsync, s.Rig.QuoteAsync)
|
||||||
|
{
|
||||||
|
ClockSkew = _ => TimeSpan.FromSeconds(3),
|
||||||
|
};
|
||||||
|
Assert.AreEqual(RiskReasons.ClockSkew, (await skewed.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task AStrategyInObservationNeverBuys()
|
||||||
|
{
|
||||||
|
await using var s = await CreateAsync();
|
||||||
|
await s.Rig.Db.WriteAsync(x => x.ExecuteAsync("UPDATE strategy_state SET stage = 'observation'", _none), _none);
|
||||||
|
Assert.AreEqual(RiskReasons.Observation, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 9.2: the limits of each world ----
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task ADayOfLossesBlocksEntriesOfThatWorldOnly()
|
||||||
|
{
|
||||||
|
await using var s = await CreateAsync();
|
||||||
|
var now = s.Rig.Clock.UtcNow;
|
||||||
|
await SnapshotAsync(s.Rig, Worlds.Simulated, now - TimeSpan.FromHours(10), 1.00m);
|
||||||
|
await SnapshotAsync(s.Rig, Worlds.Simulated, now, 0.975m);
|
||||||
|
await SnapshotAsync(s.Rig, Worlds.Real, now - TimeSpan.FromHours(10), 1.00m);
|
||||||
|
await SnapshotAsync(s.Rig, Worlds.Real, now, 1.01m);
|
||||||
|
|
||||||
|
var alerts = await s.Risk.CheckAsync([], _none);
|
||||||
|
Assert.IsTrue(alerts.Any(a => a.Kind == RiskAlertKinds.DailyLoss));
|
||||||
|
Assert.AreEqual(RiskSeverities.High, (await EventsAsync(s.Rig, RiskAlertKinds.DailyLoss)).Single());
|
||||||
|
Assert.AreEqual(RiskReasons.DailyLossBlock, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal);
|
||||||
|
Assert.IsFalse((await s.Risk.WorldAsync(Worlds.Real, _none)).EntriesBlocked, "the real world goes on");
|
||||||
|
Assert.IsNotEmpty(await s.Rig.QueryAsync("SELECT code FROM journal WHERE code = @c", r => r.Text("code"), ("c", RiskAlertKinds.DailyLoss)), "the diary says it");
|
||||||
|
|
||||||
|
// A second check does not repeat the alert; after 24 hours entries are back.
|
||||||
|
await s.Risk.CheckAsync([], _none);
|
||||||
|
Assert.HasCount(1, await EventsAsync(s.Rig, RiskAlertKinds.DailyLoss));
|
||||||
|
s.Rig.Clock.Advance(TimeSpan.FromHours(24) + _minute);
|
||||||
|
s.Rig.Refresh();
|
||||||
|
Assert.IsNull((await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task TheSwitchTripsAtFifteenPercentAndOnlyTheUserRestartsIt()
|
||||||
|
{
|
||||||
|
await using var s = await CreateAsync();
|
||||||
|
await HoldAsync(s, s.Account, 0.01m);
|
||||||
|
await SnapshotAsync(s.Rig, Worlds.Simulated, s.Rig.Clock.UtcNow, 1.00m);
|
||||||
|
await s.Risk.CheckAsync([], _none);
|
||||||
|
s.Rig.Clock.Advance(TimeSpan.FromDays(5));
|
||||||
|
await SnapshotAsync(s.Rig, Worlds.Simulated, s.Rig.Clock.UtcNow, 1.20m);
|
||||||
|
await s.Risk.CheckAsync([], _none);
|
||||||
|
|
||||||
|
// The high of ten days ago is outside the series read now, but remembered.
|
||||||
|
s.Rig.Clock.Advance(TimeSpan.FromDays(10));
|
||||||
|
s.Rig.Refresh();
|
||||||
|
await SnapshotAsync(s.Rig, Worlds.Simulated, s.Rig.Clock.UtcNow, 1.00m);
|
||||||
|
await s.Risk.CheckAsync([], _none);
|
||||||
|
var world = await s.Risk.WorldAsync(Worlds.Simulated, _none);
|
||||||
|
Assert.IsTrue(world.State.Tripped);
|
||||||
|
Assert.AreEqual(RiskSeverities.Critical, (await EventsAsync(s.Rig, RiskAlertKinds.DrawdownStop)).Single());
|
||||||
|
Assert.AreEqual(RiskReasons.SwitchTripped, (await s.Risk.GateAsync(Sell(s, 0.01m), s.Account, _none)).Refusal);
|
||||||
|
Assert.IsFalse((await s.Risk.WorldAsync(Worlds.Real, _none)).State.Tripped);
|
||||||
|
|
||||||
|
// Days pass: nothing rearms by itself.
|
||||||
|
s.Rig.Clock.Advance(TimeSpan.FromDays(3));
|
||||||
|
await s.Risk.CheckAsync([], _none);
|
||||||
|
Assert.IsTrue((await s.Risk.WorldAsync(Worlds.Simulated, _none)).State.Tripped);
|
||||||
|
|
||||||
|
await s.Risk.RestartAsync("utente", _none);
|
||||||
|
world = await s.Risk.WorldAsync(Worlds.Simulated, _none);
|
||||||
|
Assert.IsFalse(world.State.Tripped);
|
||||||
|
Assert.AreEqual(0m, world.Measures.Drawdown, "the high starts again from now");
|
||||||
|
Assert.AreEqual("active", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
|
||||||
|
Assert.AreEqual(RiskSeverities.Info, (await EventsAsync(s.Rig, "restart")).Single(), "the restart is recorded with who confirmed it");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task TenOrdersInAMinuteStopTheBot()
|
||||||
|
{
|
||||||
|
await using var s = await CreateAsync();
|
||||||
|
async Task OrdersAsync(int count, string purpose)
|
||||||
|
{
|
||||||
|
for (var i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
await s.Rig.Db.WriteAsync(x => x.ExecuteAsync(
|
||||||
|
"INSERT INTO orders (id, account_id, instrument_id, strategy, client_order_id, side, order_type, quantity, status, created_at, updated_at, purpose, submitted_at) " +
|
||||||
|
"VALUES (@id, @a, @i, 'crypto_trend', @c, 'buy', 'limit', 1, 'submitted', @t, @t, @p, @t)", _none,
|
||||||
|
("id", Ids.NewId(s.Rig.Clock)), ("a", s.Account.AccountId), ("i", s.Btc.Id), ("c", "T" + Ids.NewId(s.Rig.Clock).ToString("N")), ("t", s.Rig.Clock.UtcNow), ("p", purpose)), _none);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await OrdersAsync(9, "entry");
|
||||||
|
await OrdersAsync(5, "stop");
|
||||||
|
await s.Risk.CheckAsync([], _none);
|
||||||
|
Assert.AreEqual("active", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value, "stops do not count");
|
||||||
|
|
||||||
|
await OrdersAsync(1, "exit");
|
||||||
|
await s.Risk.CheckAsync([], _none);
|
||||||
|
Assert.AreEqual("stopped", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
|
||||||
|
// A stop is not a critical incident of SPEC 12.3: it must not hold back a promotion for 30 days.
|
||||||
|
Assert.AreEqual(RiskSeverities.High, (await EventsAsync(s.Rig, RiskReasons.OrdersPerMinute)).Single());
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task TheStopFileStopsEverythingAndBlocksTheRestart()
|
||||||
|
{
|
||||||
|
await using var s = await CreateAsync(stopFile: true);
|
||||||
|
await File.WriteAllTextAsync(s.Risk.StopFile!, "");
|
||||||
|
Assert.AreEqual(RiskReasons.BotStopped, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal, "at once, before the check");
|
||||||
|
await s.Risk.CheckAsync([], _none);
|
||||||
|
Assert.AreEqual("stopped", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
|
||||||
|
await Assert.ThrowsExactlyAsync<InvalidOperationException>(() => s.Risk.RestartAsync("utente", _none));
|
||||||
|
|
||||||
|
File.Delete(s.Risk.StopFile!);
|
||||||
|
Assert.AreEqual(RiskReasons.BotStopped, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal, "removing the file does not restart");
|
||||||
|
await s.Risk.RestartAsync("utente", _none);
|
||||||
|
Assert.IsNull((await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task StopEverythingCancelsWorkOrdersButKeepsTheStops()
|
||||||
|
{
|
||||||
|
await using var s = await CreateAsync();
|
||||||
|
var paper = s.Rig.Paper(PaperOptions.Okx(), s.Account.AccountId);
|
||||||
|
await paper.DepositAsync(100_000m, "EUR", _none);
|
||||||
|
var manager = s.Rig.Manager(paper, s.Account);
|
||||||
|
await manager.SubmitAsync(Buy(s, 0.01m) with { StartAggressive = true }, _none);
|
||||||
|
await s.Rig.TurnsAsync(manager, 2, _minute);
|
||||||
|
var stops = await paper.GetOpenOrdersAsync(_none);
|
||||||
|
Assert.HasCount(1, stops, "the stop of the position");
|
||||||
|
|
||||||
|
// A sale far from the price stays working; "Ferma tutto" cancels it and puts the stop back.
|
||||||
|
s.Rig.Quote(s.Btc.Symbol, 60_000m, 60_010m);
|
||||||
|
var held = (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Btc.Id, StrategyNames.CryptoTrend, _none))!.Quantity;
|
||||||
|
await manager.SubmitAsync(Sell(s, held), _none);
|
||||||
|
await s.Risk.StopAllAsync([manager], "utente", "stop_all", "Fermo tutto.", _none);
|
||||||
|
await s.Rig.TurnsAsync(manager, 1, _minute);
|
||||||
|
Assert.AreEqual("stopped", (await s.Settings.GetAsync(SettingsStore.BotState.Key)).Value);
|
||||||
|
Assert.AreEqual(held, (await s.Rig.Ledger.PositionAsync(s.Account.AccountId, s.Btc.Id, StrategyNames.CryptoTrend, _none))?.Quantity, "the position stays");
|
||||||
|
var open = await paper.GetOpenOrdersAsync(_none);
|
||||||
|
Assert.IsTrue(open.Any(o => o.Kind == OrderKind.Stop || o.StopPrice is not null), "the stop is there");
|
||||||
|
Assert.IsEmpty(await s.Rig.QueryAsync("SELECT id FROM executions WHERE status = 'working'", r => r.Id("id")));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 9.2: the day-trade guard ----
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task TheDayTradeGuardKeepsMeanReversionInAndCountsTheDay()
|
||||||
|
{
|
||||||
|
await using var s = await CreateAsync();
|
||||||
|
var alpaca = await s.Rig.AccountAsync(Venues.Alpaca, TradingEnvironments.Simulation);
|
||||||
|
var stocks = new List<Instrument>();
|
||||||
|
foreach (var symbol in new[] { "AAA", "BBB", "CCC", "DDD" })
|
||||||
|
{
|
||||||
|
var stock = await s.Rig.InstrumentAsync(TradingRig.Stock(symbol));
|
||||||
|
s.Rig.Quote(symbol, 99.99m, 100m);
|
||||||
|
stocks.Add(stock);
|
||||||
|
}
|
||||||
|
|
||||||
|
await new FxStore(s.Rig.Db, s.Rig.Clock).UpsertAsync([new FxRate("EUR", "USD", DateOnly.FromDateTime(s.Rig.Clock.UtcNow.UtcDateTime), 1.10m, "test")], _none);
|
||||||
|
await s.Rig.Ledger.RecordCapitalAsync(alpaca.AccountId, StrategyNames.EquityMeanrev, 5_000m, "USD", "test", _none);
|
||||||
|
await s.Rig.Ledger.RecordCapitalAsync(alpaca.AccountId, StrategyNames.EquityMomentum, 5_000m, "USD", "test", _none);
|
||||||
|
await s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(alpaca, stocks[0], StrategyNames.EquityMeanrev, OrderSide.Buy, 1m, 100m), _none);
|
||||||
|
await s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(alpaca, stocks[1], StrategyNames.EquityMomentum, OrderSide.Buy, 1m, 100m), _none);
|
||||||
|
|
||||||
|
// Off by default: mean reversion may leave on the day it entered.
|
||||||
|
Assert.IsNull((await s.Risk.GateAsync(Sell(s, 1m, StrategyNames.EquityMeanrev, instrument: stocks[0]), alpaca, _none)).Refusal);
|
||||||
|
|
||||||
|
await s.Settings.SetAsync(RiskSettings.PdtGuard.Key, "on", "test");
|
||||||
|
Assert.AreEqual(RiskEngine.PdtReason, (await s.Risk.GateAsync(Sell(s, 1m, StrategyNames.EquityMeanrev, instrument: stocks[0]), alpaca, _none)).Refusal);
|
||||||
|
Assert.IsNull((await s.Risk.GateAsync(Sell(s, 1m, StrategyNames.EquityMomentum, instrument: stocks[1]), alpaca, _none)).Refusal);
|
||||||
|
|
||||||
|
// Two positions opened today: one more allowed, then none.
|
||||||
|
Assert.AreEqual(1, await s.Risk.PdtRoomAsync(alpaca.AccountId, _none));
|
||||||
|
Assert.IsNull((await s.Risk.GateAsync(Buy(s, 1m, StrategyNames.EquityMomentum, stocks[2]) with { StopLevel = 99m }, alpaca, _none)).Refusal);
|
||||||
|
await s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(alpaca, stocks[2], StrategyNames.EquityMomentum, OrderSide.Buy, 1m, 100m), _none);
|
||||||
|
Assert.AreEqual(RiskEngine.PdtReason, (await s.Risk.GateAsync(Buy(s, 1m, StrategyNames.EquityMomentum, stocks[3]) with { StopLevel = 99m }, alpaca, _none)).Refusal);
|
||||||
|
|
||||||
|
// Crypto is not touched by it.
|
||||||
|
Assert.IsNull((await s.Risk.GateAsync(Buy(s, 0.001m), s.Account, _none)).Refusal);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 12.4: real money only with the procedure ----
|
||||||
|
|
||||||
|
private sealed record Live(FaultyBroker Broker, PaperBroker Paper, AccountContext Account, OrderManager Manager);
|
||||||
|
|
||||||
|
/// <summary>A fake real account: the simulator behind a broker that says "live", and its order manager wired as in the service.</summary>
|
||||||
|
private static async Task<Live> FakeRealAccountAsync(Setup s, bool permit = true)
|
||||||
|
{
|
||||||
|
var account = await s.Rig.AccountAsync(Venues.Okx, TradingEnvironments.Live, "OKX reale (finto)");
|
||||||
|
var paper = s.Rig.Paper(PaperOptions.Okx(), account.AccountId);
|
||||||
|
await paper.DepositAsync(100_000m, "EUR", _none);
|
||||||
|
var broker = new FaultyBroker(paper, TradingEnvironments.Live);
|
||||||
|
var manager = new OrderManager(s.Rig.Db, s.Rig.Clock, s.Rig.Ledger, broker, account, TradingRig.Installation, s.Rig.FindAsync, s.Rig.QuoteAsync)
|
||||||
|
{
|
||||||
|
ConfirmPrice = s.Rig.QuoteAsync,
|
||||||
|
MarketOpen = (_, _) => Task.FromResult(true),
|
||||||
|
Gate = s.Risk.GateAsync,
|
||||||
|
LivePermit = permit ? s.Stages.LiveRefusalAsync : null,
|
||||||
|
};
|
||||||
|
s.Owned.Add(manager);
|
||||||
|
return new Live(broker, paper, account, manager);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Everything SPEC 12.3 asks before reduced real: 60 days, 8 closed trades, the one-step comparison, the backtest passed.</summary>
|
||||||
|
private static async Task RequirementsMetAsync(Setup s)
|
||||||
|
{
|
||||||
|
var since = s.Rig.Clock.UtcNow - TimeSpan.FromDays(61);
|
||||||
|
await s.Rig.Db.WriteAsync(x => x.ExecuteAsync("UPDATE strategy_state SET stage_since = @t", _none, ("t", since)), _none);
|
||||||
|
await s.Stages.ApplyQualificationAsync(StrategyNames.CryptoTrend, new Qualification
|
||||||
|
{
|
||||||
|
Passed = true,
|
||||||
|
Verdict = "superato",
|
||||||
|
Report = "docs/backtests/crypto_trend.md",
|
||||||
|
MaxDrawdown = 0.20m,
|
||||||
|
ExpectedSlippageBp = 5m,
|
||||||
|
RoundTripCost = 0.004m,
|
||||||
|
}, _none);
|
||||||
|
for (var i = 0; i < 8; i++)
|
||||||
|
{
|
||||||
|
var closed = since + TimeSpan.FromDays(5 + (i * 6));
|
||||||
|
await s.Rig.Db.WriteAsync(x => x.ExecuteAsync(
|
||||||
|
"INSERT INTO trades (id, account_id, instrument_id, strategy, status, opened_at, closed_at, bought_quantity, bought_value, sold_quantity, sold_value, fees, realized, created_at, updated_at) " +
|
||||||
|
"VALUES (@id, @a, @i, 'crypto_trend', 'closed', @o, @c, 0.01, 600, 0.01, 620, 1, 19, @c, @c)", _none,
|
||||||
|
("id", Ids.NewId(s.Rig.Clock)), ("a", s.Account.AccountId), ("i", s.Btc.Id), ("o", closed - TimeSpan.FromDays(3)), ("c", closed)), _none);
|
||||||
|
await new DecisionLog(s.Rig.Db, s.Rig.Clock).WriteAsync(new DecisionRow(Ids.NewId(s.Rig.Clock), StrategyNames.CryptoTrend, s.Account.AccountId, null, DecisionStages.OneStep,
|
||||||
|
DecisionOutcomes.Same, [], null, closed), _none);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Simulation)]
|
||||||
|
public async Task NoOrderReachesARealAccountWithoutTheProcedure()
|
||||||
|
{
|
||||||
|
// Without the startup consent: nothing, however the strategy stands.
|
||||||
|
await using (var s = await CreateAsync())
|
||||||
|
{
|
||||||
|
var live = await FakeRealAccountAsync(s);
|
||||||
|
var (id, refusal) = await live.Manager.SubmitAsync(Buy(s, 0.001m), _none);
|
||||||
|
Assert.IsNull(id);
|
||||||
|
Assert.AreEqual(RiskReasons.NoConsent, refusal);
|
||||||
|
await RequirementsMetAsync(s);
|
||||||
|
var refused = await Assert.ThrowsExactlyAsync<LiveConfirmationException>(() => s.Stages.ConfirmLiveAsync(
|
||||||
|
new LiveConfirmation(StrategyNames.CryptoTrend, live.Account.AccountId, StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Reduced), Password, null, "utente"), _none));
|
||||||
|
Assert.AreEqual(RiskReasons.NoConsent, refused.Code);
|
||||||
|
await s.Rig.TurnsAsync(live.Manager, 3, _minute);
|
||||||
|
Assert.IsEmpty(live.Broker.Sent);
|
||||||
|
}
|
||||||
|
|
||||||
|
// An order manager without the permission check sends nothing on a real account: it fails closed.
|
||||||
|
await using (var s = await CreateAsync(Consent()))
|
||||||
|
{
|
||||||
|
var bare = await FakeRealAccountAsync(s, permit: false);
|
||||||
|
Assert.AreEqual(RiskReasons.LiveNotConfirmed, (await bare.Manager.SubmitAsync(Buy(s, 0.001m), _none)).Refusal);
|
||||||
|
Assert.IsEmpty(bare.Broker.Sent);
|
||||||
|
}
|
||||||
|
|
||||||
|
// With the consent, step by step: every part of the procedure is needed.
|
||||||
|
await using (var s = await CreateAsync(Consent()))
|
||||||
|
{
|
||||||
|
var live = await FakeRealAccountAsync(s);
|
||||||
|
await s.Rig.Ledger.RecordCapitalAsync(live.Account.AccountId, StrategyNames.CryptoTrend, 2_500m, "EUR", "test", _none);
|
||||||
|
Assert.AreEqual(RiskReasons.LiveNotConfirmed, (await live.Manager.SubmitAsync(Buy(s, 0.001m), _none)).Refusal, "simulation is not real money");
|
||||||
|
await Assert.ThrowsExactlyAsync<LiveConfirmationException>(() => s.Stages.MoveAsync(StrategyNames.CryptoTrend, StrategyStages.Reduced, "test", "utente", _none),
|
||||||
|
"no shortcut to real money");
|
||||||
|
|
||||||
|
var phrase = StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Reduced);
|
||||||
|
LiveConfirmation Ask(string text, string password) => new(StrategyNames.CryptoTrend, live.Account.AccountId, text, password, null, "utente");
|
||||||
|
Assert.AreEqual("requirements", (await Assert.ThrowsExactlyAsync<LiveConfirmationException>(() => s.Stages.ConfirmLiveAsync(Ask(phrase, Password), _none))).Code);
|
||||||
|
|
||||||
|
await RequirementsMetAsync(s);
|
||||||
|
Assert.IsTrue((await s.Stages.RequirementsAsync(StrategyNames.CryptoTrend, _none)).All(r => r.Met));
|
||||||
|
Assert.AreEqual("phrase", (await Assert.ThrowsExactlyAsync<LiveConfirmationException>(() => s.Stages.ConfirmLiveAsync(Ask("confermo", Password), _none))).Code);
|
||||||
|
Assert.AreEqual("password", (await Assert.ThrowsExactlyAsync<LiveConfirmationException>(() => s.Stages.ConfirmLiveAsync(Ask(phrase, "sbagliata"), _none))).Code);
|
||||||
|
await s.Rig.TurnsAsync(live.Manager, 2, _minute);
|
||||||
|
Assert.IsEmpty(live.Broker.Sent, "nothing reached the real account before the confirmation");
|
||||||
|
|
||||||
|
s.Rig.Refresh();
|
||||||
|
await s.Stages.ConfirmLiveAsync(Ask(phrase, Password), _none);
|
||||||
|
var stage = (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!;
|
||||||
|
Assert.AreEqual(StrategyStages.Reduced, stage.Stage);
|
||||||
|
Assert.AreEqual(live.Account.AccountId, stage.LiveAccountId);
|
||||||
|
Assert.IsNotNull(stage.LiveConfirmedAt);
|
||||||
|
Assert.IsNotEmpty(await s.Rig.QueryAsync("SELECT key FROM config_history WHERE key = @k", r => r.Text("key"), ("k", "strategy.crypto_trend.stage")));
|
||||||
|
Assert.IsNotEmpty(await s.Rig.QueryAsync("SELECT to_stage FROM strategy_stage_history WHERE to_stage = 'reduced'", r => r.Text("to_stage")));
|
||||||
|
|
||||||
|
var (id, refusal) = await live.Manager.SubmitAsync(Buy(s, 0.001m) with { StartAggressive = true }, _none);
|
||||||
|
Assert.IsNull(refusal);
|
||||||
|
Assert.IsNotNull(id);
|
||||||
|
await s.Rig.TurnsAsync(live.Manager, 2, _minute);
|
||||||
|
Assert.IsNotEmpty(live.Broker.Sent, "after the procedure the order reaches the account");
|
||||||
|
|
||||||
|
// Another strategy on the same account is still refused: the confirmation is for one strategy and one account.
|
||||||
|
Assert.AreEqual(RiskReasons.LiveNotConfirmed, (await live.Manager.SubmitAsync(Buy(s, 0.001m, StrategyNames.EquityMomentum), _none)).Refusal);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Simulation)]
|
||||||
|
public async Task ADemotedStrategyKeepsManagingItsRealPositionsDownToZero()
|
||||||
|
{
|
||||||
|
await using var s = await CreateAsync(Consent());
|
||||||
|
var live = await FakeRealAccountAsync(s);
|
||||||
|
await s.Rig.Ledger.RecordCapitalAsync(live.Account.AccountId, StrategyNames.CryptoTrend, 2_500m, "EUR", "test", _none);
|
||||||
|
await RequirementsMetAsync(s);
|
||||||
|
await s.Stages.ConfirmLiveAsync(new LiveConfirmation(StrategyNames.CryptoTrend, live.Account.AccountId,
|
||||||
|
StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Reduced), Password, null, "utente"), _none);
|
||||||
|
s.Rig.Refresh();
|
||||||
|
await live.Manager.SubmitAsync(Buy(s, 0.002m) with { StartAggressive = true }, _none);
|
||||||
|
await s.Rig.TurnsAsync(live.Manager, 3, _minute);
|
||||||
|
var held = (await s.Rig.Ledger.PositionAsync(live.Account.AccountId, s.Btc.Id, StrategyNames.CryptoTrend, _none))!.Quantity;
|
||||||
|
Assert.IsTrue(held is > 0.0019m and <= 0.002m, "bought, less the fee in bitcoin");
|
||||||
|
Assert.HasCount(1, await live.Paper.GetOpenOrdersAsync(_none), "the stop on the real account");
|
||||||
|
|
||||||
|
await s.Stages.DemoteAsync(StrategyNames.CryptoTrend, "drawdown", _none);
|
||||||
|
var stage = (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!;
|
||||||
|
Assert.AreEqual(StrategyStages.Simulation, stage.Stage);
|
||||||
|
Assert.IsTrue(stage.ExitOnly);
|
||||||
|
Assert.IsNull(stage.LiveConfirmedAt);
|
||||||
|
Assert.AreEqual(RiskSeverities.High, (await EventsAsync(s.Rig, "demotion")).Single());
|
||||||
|
|
||||||
|
// Nothing new, nothing bigger.
|
||||||
|
var sent = live.Broker.Sent.Count;
|
||||||
|
Assert.AreEqual(RiskReasons.ExitOnly, (await live.Manager.SubmitAsync(Buy(s, 0.001m), _none)).Refusal);
|
||||||
|
|
||||||
|
// The stops are kept and put back every day: one moved by hand comes back.
|
||||||
|
foreach (var order in await live.Paper.GetOpenOrdersAsync(_none))
|
||||||
|
{
|
||||||
|
await live.Paper.CancelOrderAsync(order.ClientOrderId, order.Symbol, _none);
|
||||||
|
}
|
||||||
|
|
||||||
|
await s.Rig.TurnsAsync(live.Manager, 2, _minute);
|
||||||
|
Assert.HasCount(1, await live.Paper.GetOpenOrdersAsync(_none), "the stop is put back on the real account");
|
||||||
|
|
||||||
|
// The exit goes: half, then the rest.
|
||||||
|
Assert.IsNull((await live.Manager.SubmitAsync(Sell(s, 0.001m) with { StartAggressive = true }, _none)).Refusal);
|
||||||
|
await s.Rig.TurnsAsync(live.Manager, 3, _minute);
|
||||||
|
var rest = (await s.Rig.Ledger.PositionAsync(live.Account.AccountId, s.Btc.Id, StrategyNames.CryptoTrend, _none))!.Quantity;
|
||||||
|
Assert.AreEqual(held - 0.001m, rest);
|
||||||
|
Assert.AreEqual(0, await s.Stages.ReleaseExitOnlyAsync(s.Rig.Ledger, _none), "a real position is still open");
|
||||||
|
Assert.IsNull((await live.Manager.SubmitAsync(Sell(s, rest) with { StartAggressive = true }, _none)).Refusal);
|
||||||
|
await s.Rig.TurnsAsync(live.Manager, 3, _minute);
|
||||||
|
Assert.IsNull(await s.Rig.Ledger.PositionAsync(live.Account.AccountId, s.Btc.Id, StrategyNames.CryptoTrend, _none) is { Quantity: > 0m } p ? p : null);
|
||||||
|
Assert.IsTrue(live.Broker.Sent.Count > sent);
|
||||||
|
|
||||||
|
// At zero the exit only ends, and the real account is closed to it again.
|
||||||
|
Assert.AreEqual(1, await s.Stages.ReleaseExitOnlyAsync(s.Rig.Ledger, _none));
|
||||||
|
Assert.IsFalse((await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!.ExitOnly);
|
||||||
|
Assert.AreEqual(RiskReasons.LiveNotConfirmed, (await live.Manager.SubmitAsync(Buy(s, 0.001m), _none)).Refusal);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task TheTwinIsPhotographedButLeftOutOfTheTotals()
|
||||||
|
{
|
||||||
|
await using var s = await CreateAsync(Consent());
|
||||||
|
var live = await s.Rig.AccountAsync(Venues.Okx, TradingEnvironments.Live, "OKX reale (finto)");
|
||||||
|
await s.Rig.Ledger.RecordCapitalAsync(live.AccountId, StrategyNames.CryptoTrend, 2_500m, "EUR", "test", _none);
|
||||||
|
await s.Rig.Db.WriteAsync(x => x.ExecuteAsync("UPDATE strategy_state SET stage = 'reduced', live_account_id = @a, live_confirmed_at = @t", _none,
|
||||||
|
("a", live.AccountId), ("t", s.Rig.Clock.UtcNow)), _none);
|
||||||
|
await new EquityBook(s.Rig.Db, s.Rig.Clock, s.Rig.Ledger, new FxStore(s.Rig.Db, s.Rig.Clock)).TakeAsync(_none);
|
||||||
|
var totals = await s.Rig.QueryAsync("SELECT world, equity FROM equity_snapshots WHERE scope = 'total'", r => (World: r.Text("world"), Equity: r.Money("equity")));
|
||||||
|
Assert.AreEqual(2_500m, totals.Single(t => t.World == Worlds.Real).Equity);
|
||||||
|
Assert.IsFalse(totals.Any(t => t.World == Worlds.Simulated), "the twin is the only simulated ledger");
|
||||||
|
Assert.HasCount(2, await s.Rig.QueryAsync("SELECT id FROM equity_snapshots WHERE scope = 'strategy'", r => r.Id("id")));
|
||||||
|
|
||||||
|
// In the risk engine too: the twin's ten thousand are not exposure, and the reference counts the quarter four times.
|
||||||
|
var exposure = await s.Risk.ExposureAsync(_none);
|
||||||
|
Assert.AreEqual(0m, exposure.SimulatedEquity);
|
||||||
|
Assert.AreEqual(2_500m, exposure.RealEquity);
|
||||||
|
Assert.AreEqual(10_000m, await s.Risk.ReferenceAsync(_none));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task TheReferenceCountsEachResultOnceAcrossStageChanges()
|
||||||
|
{
|
||||||
|
await using var s = await CreateAsync(Consent());
|
||||||
|
var live = await s.Rig.AccountAsync(Venues.Okx, TradingEnvironments.Live, "OKX reale (finto)");
|
||||||
|
async Task TradeAsync(AccountContext account, decimal quantity, decimal sold)
|
||||||
|
{
|
||||||
|
await s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(account, s.Btc, StrategyNames.CryptoTrend, OrderSide.Buy, quantity, 60_000m), _none);
|
||||||
|
await s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(account, s.Btc, StrategyNames.CryptoTrend, OrderSide.Sell, quantity, sold), _none);
|
||||||
|
}
|
||||||
|
|
||||||
|
Task<decimal> ResultsAsync(AccountContext account) => s.Rig.Db.ReadAsync(x => StageBook.LedgerResultsAsync(x, account.AccountId, StrategyNames.CryptoTrend), _none);
|
||||||
|
|
||||||
|
// In simulation: the capital and what the simulation made.
|
||||||
|
await TradeAsync(s.Account, 0.1m, 70_000m);
|
||||||
|
var simulated = await ResultsAsync(s.Account);
|
||||||
|
Assert.AreEqual(10_000m + simulated, await s.Risk.ReferenceAsync(_none));
|
||||||
|
|
||||||
|
// Reduced real: the simulation's results stay, the quarter on the real account counts four times.
|
||||||
|
await RequirementsMetAsync(s);
|
||||||
|
await s.Rig.Ledger.RecordCapitalAsync(live.AccountId, StrategyNames.CryptoTrend, 2_500m, "EUR", "test", _none);
|
||||||
|
await s.Stages.ConfirmLiveAsync(new LiveConfirmation(StrategyNames.CryptoTrend, live.AccountId, StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Reduced),
|
||||||
|
Password, null, "utente"), _none);
|
||||||
|
await TradeAsync(live, 0.01m, 66_000m);
|
||||||
|
var reduced = await ResultsAsync(live);
|
||||||
|
await TradeAsync(s.Account, 0.05m, 50_000m); // the twin's results are not part of the reference
|
||||||
|
Assert.AreEqual(10_000m + simulated + (4m * reduced), await s.Risk.ReferenceAsync(_none));
|
||||||
|
|
||||||
|
// Real, on the same ledger: what was made in reduced is counted once, four times, not five.
|
||||||
|
s.Rig.Clock.Advance(TimeSpan.FromDays(31));
|
||||||
|
await s.Rig.Ledger.RecordCapitalAsync(live.AccountId, StrategyNames.CryptoTrend, 7_500m, "EUR", "test", _none);
|
||||||
|
await s.Stages.ConfirmLiveAsync(new LiveConfirmation(StrategyNames.CryptoTrend, live.AccountId, StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Real),
|
||||||
|
Password, null, "utente"), _none);
|
||||||
|
Assert.AreEqual(10_000m + simulated + (4m * reduced), await s.Risk.ReferenceAsync(_none));
|
||||||
|
|
||||||
|
// Back to simulation: the simulation's old results are not counted again, nor the twin's.
|
||||||
|
await s.Stages.RevokeAsync(StrategyNames.CryptoTrend, "utente", "user", _none);
|
||||||
|
Assert.AreEqual(10_000m + simulated + (4m * reduced), await s.Risk.ReferenceAsync(_none));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task AnInstrumentBelongsToOneStrategyPerAccountAndPurchasesUnderWayHoldTheirCash()
|
||||||
|
{
|
||||||
|
await using var s = await CreateAsync();
|
||||||
|
|
||||||
|
// SPEC 8.6: another strategy holds BTC in this account, crypto_trend skips the entry.
|
||||||
|
await s.Rig.Ledger.RecordCapitalAsync(s.Account.AccountId, "sma_cross", 10_000m, "EUR", "test", _none);
|
||||||
|
await HoldAsync(s, s.Account, 0.01m, "sma_cross");
|
||||||
|
Assert.AreEqual(RiskReasons.OwnedByOther, (await s.Risk.GateAsync(Buy(s, 0.01m), s.Account, _none)).Refusal);
|
||||||
|
await s.Rig.Ledger.RecordFillAsync(s.Rig.Fill(s.Account, s.Btc, "sma_cross", OrderSide.Sell, 0.01m, 60_000m), _none);
|
||||||
|
Assert.IsNull((await s.Risk.GateAsync(Buy(s, 0.001m), s.Account, _none)).Refusal);
|
||||||
|
|
||||||
|
// A purchase of 9 600 € still under way holds its cash: only what is left can be bought, at the highest price.
|
||||||
|
await s.Rig.Db.WriteAsync(x => x.ExecuteAsync(
|
||||||
|
"INSERT INTO executions (id, account_id, instrument_id, strategy, side, purpose, quantity, filled, order_key, sequence, step, reference_price, status, started_at, created_at, updated_at) " +
|
||||||
|
"VALUES (@id, @a, @i, @s, 'buy', 'entry', 0.16, 0, 'K1', 1, 0, 60000, @w, @t, @t, @t)", _none,
|
||||||
|
("id", Ids.NewId(s.Rig.Clock)), ("a", s.Account.AccountId), ("i", s.Btc.Id), ("s", StrategyNames.CryptoTrend), ("w", ExecutionStates.Working), ("t", s.Rig.Clock.UtcNow)), _none);
|
||||||
|
var highest = 1m + RiskLimits.Default.MaxPriceGap;
|
||||||
|
var result = await s.Risk.GateAsync(Buy(s, 0.5m), s.Account, _none);
|
||||||
|
Assert.AreEqual(RiskReasons.NoLeverage, result.Reasons[^1]);
|
||||||
|
Assert.IsLessThanOrEqualTo(10_000m - (9_600m * highest) + 0.01m, result.Quantity * 60_010m * highest);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task ObservationLastsNinetyDaysBeforeTheSimulation()
|
||||||
|
{
|
||||||
|
await using var s = await CreateAsync();
|
||||||
|
await s.Rig.Db.WriteAsync(x => x.ExecuteAsync("UPDATE strategy_state SET stage = 'observation', stage_since = @t", _none, ("t", s.Rig.Clock.UtcNow)), _none);
|
||||||
|
var passed = new Qualification { Passed = true, Verdict = "superato", Report = "docs/backtests/crypto_trend.md" };
|
||||||
|
await s.Stages.ApplyQualificationAsync(StrategyNames.CryptoTrend, passed with { Passed = false, Verdict = "non superato" }, _none);
|
||||||
|
|
||||||
|
// SPEC 12.3: the protocol passed and 90 days of signals collected live.
|
||||||
|
var refused = await Assert.ThrowsExactlyAsync<LiveConfirmationException>(() => s.Stages.MoveAsync(StrategyNames.CryptoTrend, StrategyStages.Simulation, "user", "utente", _none));
|
||||||
|
Assert.AreEqual("backtest", refused.Code);
|
||||||
|
// A new outcome after the first start: written as the first start would, without its automatic move.
|
||||||
|
await s.Rig.Db.WriteAsync(x => x.ExecuteAsync("UPDATE strategy_state SET qualification = @q", _none,
|
||||||
|
("q", new DbJson(System.Text.Json.JsonSerializer.Serialize(passed, Qualification.Json)))), _none);
|
||||||
|
s.Rig.Clock.Advance(TimeSpan.FromDays(89));
|
||||||
|
refused = await Assert.ThrowsExactlyAsync<LiveConfirmationException>(() => s.Stages.MoveAsync(StrategyNames.CryptoTrend, StrategyStages.Simulation, "user", "utente", _none));
|
||||||
|
Assert.AreEqual("observation", refused.Code);
|
||||||
|
var requirement = (await s.Stages.RequirementsAsync(StrategyNames.CryptoTrend, _none)).Single(r => r.Key == "observation");
|
||||||
|
Assert.IsFalse(requirement.Met);
|
||||||
|
|
||||||
|
s.Rig.Clock.Advance(TimeSpan.FromDays(1));
|
||||||
|
await s.Stages.MoveAsync(StrategyNames.CryptoTrend, StrategyStages.Simulation, "user", "utente", _none);
|
||||||
|
Assert.AreEqual(StrategyStages.Simulation, (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!.Stage);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task WithRealMoneyTheQualificationDoesNotMove()
|
||||||
|
{
|
||||||
|
await using var s = await CreateAsync(Consent());
|
||||||
|
var live = await s.Rig.AccountAsync(Venues.Okx, TradingEnvironments.Live, "OKX reale (finto)");
|
||||||
|
await RequirementsMetAsync(s);
|
||||||
|
await s.Stages.ConfirmLiveAsync(new LiveConfirmation(StrategyNames.CryptoTrend, live.AccountId, StageBook.Phrase(StrategyNames.CryptoTrend, StrategyStages.Reduced),
|
||||||
|
Password, null, "utente"), _none);
|
||||||
|
|
||||||
|
// SPEC 12.3: a new build cannot move the figures a strategy with real money is compared with.
|
||||||
|
await s.Stages.ApplyQualificationAsync(StrategyNames.CryptoTrend, new Qualification { Passed = true, Verdict = "altro", Report = "altro.md", MaxDrawdown = 0.50m }, _none);
|
||||||
|
Assert.AreEqual(0.20m, (await s.Stages.GetAsync(StrategyNames.CryptoTrend, _none))!.Qualification!.MaxDrawdown);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,455 @@
|
|||||||
|
using Anubis.Backtest;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Risk;
|
||||||
|
using Anubis.Strategies;
|
||||||
|
|
||||||
|
namespace Anubis.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The rules of the risk engine without a database (issues #41, #42; SPEC 8.5, 9.1, 9.2, 9.5): every size rule, the
|
||||||
|
/// monitor of losses with its blocks, warnings and switch, the scenarios, the correctives.
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class RiskTests
|
||||||
|
{
|
||||||
|
private static readonly RiskLimits _limits = RiskLimits.Default;
|
||||||
|
|
||||||
|
// A Wednesday in November: 11:00 in Rome.
|
||||||
|
private static readonly DateTimeOffset _now = new(2026, 11, 11, 10, 0, 0, TimeSpan.Zero);
|
||||||
|
|
||||||
|
private static PurchaseRequest Request(decimal wanted, decimal price = 100m, decimal held = 0m, decimal? stop = 95m, decimal reference = 10_000m) => new()
|
||||||
|
{
|
||||||
|
Price = price,
|
||||||
|
Held = held,
|
||||||
|
Wanted = wanted,
|
||||||
|
Stop = stop,
|
||||||
|
WorldEquity = reference,
|
||||||
|
WorldInvested = 0m,
|
||||||
|
Reference = reference,
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---- 9.2: each limit on the size of a purchase ----
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheInvestedCapitalLimitStopsPurchasesAtTheEquity()
|
||||||
|
{
|
||||||
|
var size = RiskRules.SizePurchase(Request(10m) with { WorldInvested = 9_700m }, _limits);
|
||||||
|
Assert.AreEqual(3m, size.Quantity);
|
||||||
|
CollectionAssert.Contains(size.Reasons.ToList(), RiskReasons.InvestedLimit);
|
||||||
|
Assert.AreEqual(0m, RiskRules.SizePurchase(Request(10m) with { WorldInvested = 10_000m }, _limits).Quantity);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void OnePositionNeverWeighsMoreThanTwentyPercentOfTheReference()
|
||||||
|
{
|
||||||
|
// 20% of 10 000 at 100 is 20 shares: 15 held, 5 more allowed.
|
||||||
|
var size = RiskRules.SizePurchase(Request(10m, held: 15m, stop: 99.5m), _limits);
|
||||||
|
Assert.AreEqual(5m, size.Quantity);
|
||||||
|
CollectionAssert.Contains(size.Reasons.ToList(), RiskReasons.PositionLimit);
|
||||||
|
|
||||||
|
// Heavier than the threshold: the excess goes at the first chance.
|
||||||
|
Assert.AreEqual(10m, RiskRules.Excess(30m, 100m, 10_000m, _limits));
|
||||||
|
Assert.AreEqual(0m, RiskRules.Excess(20m, 100m, 10_000m, _limits));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void CryptoNeverGoesBeyondFortyPercentOfTheReference()
|
||||||
|
{
|
||||||
|
var size = RiskRules.SizePurchase(Request(10m, stop: 99.5m) with { IsCrypto = true, CryptoValue = 3_900m }, _limits);
|
||||||
|
Assert.AreEqual(1m, size.Quantity);
|
||||||
|
CollectionAssert.Contains(size.Reasons.ToList(), RiskReasons.CryptoLimit);
|
||||||
|
|
||||||
|
// The same purchase of a stock is not touched by the crypto share.
|
||||||
|
Assert.AreEqual(10m, RiskRules.SizePurchase(Request(10m, stop: 99.5m) with { CryptoValue = 3_900m }, _limits).Quantity);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheRiskOfOneTradeIsAtMostOnePercentOnTheWholePosition()
|
||||||
|
{
|
||||||
|
// 1% of 10 000 is 100; with the stop 10 below the price that is 10 shares for the whole position.
|
||||||
|
var size = RiskRules.SizePurchase(Request(15m, stop: 90m), _limits);
|
||||||
|
Assert.AreEqual(10m, size.Quantity);
|
||||||
|
CollectionAssert.Contains(size.Reasons.ToList(), RiskReasons.TradeRiskLimit);
|
||||||
|
Assert.AreEqual(6m, RiskRules.SizePurchase(Request(15m, held: 4m, stop: 90m), _limits).Quantity);
|
||||||
|
|
||||||
|
// Without a stop the whole value is at risk; a stop at or above the price buys nothing.
|
||||||
|
Assert.AreEqual(1m, RiskRules.SizePurchase(Request(15m, stop: null), _limits).Quantity);
|
||||||
|
var above = RiskRules.SizePurchase(Request(15m, stop: 100m), _limits);
|
||||||
|
Assert.AreEqual(0m, above.Quantity);
|
||||||
|
CollectionAssert.Contains(above.Reasons.ToList(), RiskReasons.StopAbovePrice);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void AReductionMultipliesTheTargetAndNeverSellsWhatIsHeld()
|
||||||
|
{
|
||||||
|
var halved = RiskRules.SizePurchase(Request(10m, stop: 99.5m) with { Multiplier = 0.5m }, _limits);
|
||||||
|
Assert.AreEqual(5m, halved.Quantity);
|
||||||
|
CollectionAssert.Contains(halved.Reasons.ToList(), RiskReasons.Reduction);
|
||||||
|
|
||||||
|
// 6 held towards a target of 10, halved to 5: nothing more is bought, nothing is sold.
|
||||||
|
Assert.AreEqual(0m, RiskRules.SizePurchase(Request(4m, held: 6m, stop: 99.5m) with { Multiplier = 0.5m }, _limits).Quantity);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 9.1 points 5 and 6, as properties ----
|
||||||
|
|
||||||
|
private sealed record Case(PurchaseRequest Request, decimal Loss, decimal Cut)
|
||||||
|
{
|
||||||
|
public override string ToString() => $"{Request} loss {Loss} cut {Cut}";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Case Generate(Gen g)
|
||||||
|
{
|
||||||
|
var price = (decimal)Math.Round(1 + (g.Double() * 1000), 2);
|
||||||
|
var reference = (decimal)Math.Round(1_000 + (g.Double() * 100_000), 2);
|
||||||
|
var request = new PurchaseRequest
|
||||||
|
{
|
||||||
|
Price = price,
|
||||||
|
Held = g.Bool() ? 0m : (decimal)Math.Round(g.Double() * 50, 4),
|
||||||
|
Wanted = (decimal)Math.Round(g.Double() * 100, 4),
|
||||||
|
Stop = g.Int(0, 4) switch
|
||||||
|
{
|
||||||
|
0 => null,
|
||||||
|
1 => price * 1.01m,
|
||||||
|
_ => Math.Round(price * (decimal)(0.5 + (g.Double() * 0.49)), 2),
|
||||||
|
},
|
||||||
|
Multiplier = g.Bool() ? 1m : (decimal)Math.Round(g.Double(), 2),
|
||||||
|
WorldEquity = reference,
|
||||||
|
WorldInvested = (decimal)Math.Round(g.Double() * (double)reference, 2),
|
||||||
|
Reference = reference,
|
||||||
|
IsCrypto = g.Bool(),
|
||||||
|
CryptoValue = (decimal)Math.Round(g.Double() * 0.5 * (double)reference, 2),
|
||||||
|
};
|
||||||
|
return new Case(request, (decimal)Math.Round(g.Double() * 0.5, 4), (decimal)Math.Round(g.Double(), 4));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void NoRuleEverEnlargesWhatTheStrategyAsked() =>
|
||||||
|
Property.ForAll(Generate, c =>
|
||||||
|
{
|
||||||
|
var size = RiskRules.SizePurchase(c.Request, _limits);
|
||||||
|
Assert.IsTrue(size.Quantity >= 0m && size.Quantity <= c.Request.Wanted, $"{size.Quantity} for {c.Request.Wanted}");
|
||||||
|
});
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void AfterALossNoPurchaseIsLarger() =>
|
||||||
|
Property.ForAll(Generate, c =>
|
||||||
|
{
|
||||||
|
// The same purchase after a loss: less equity, a lower reference, a multiplier no higher. No doubling, no recovery.
|
||||||
|
var before = RiskRules.SizePurchase(c.Request, _limits).Quantity;
|
||||||
|
var factor = 1m - c.Loss;
|
||||||
|
var after = RiskRules.SizePurchase(c.Request with
|
||||||
|
{
|
||||||
|
WorldEquity = c.Request.WorldEquity * factor,
|
||||||
|
Reference = c.Request.Reference * factor,
|
||||||
|
Multiplier = c.Request.Multiplier * (1m - (c.Cut / 2m)),
|
||||||
|
}, _limits).Quantity;
|
||||||
|
Assert.IsTrue(after <= before, $"{after} after the loss, {before} before");
|
||||||
|
});
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void NoCorrectiveRaisesAWeight()
|
||||||
|
{
|
||||||
|
var holdings = new Dictionary<string, Holding> { ["AAA"] = new(10m, 100m, 90m, StrategyData.Start) };
|
||||||
|
var bars = StrategyData.Series(StrategyData.FromCloses([100, 100, 100]));
|
||||||
|
var context = new StrategyContext(StrategyData.Start.AddDays(2), default, ["AAA", "BBB"], new PortfolioView(9_000m, 10_000m, holdings), _ => bars, _ => null);
|
||||||
|
Property.ForAll(g => (Symbol: g.Bool() ? "AAA" : "BBB", Target: (decimal)Math.Round(g.Double() * 0.5, 4), Multiplier: (decimal)Math.Round(g.Double() * 1.5, 4)), c =>
|
||||||
|
{
|
||||||
|
var intent = new Intent(c.Symbol, c.Target, "test") { Stop = 90m };
|
||||||
|
var reduced = BookWeights.Reduce(context, intent, c.Multiplier, CorrectiveReasons.CalendarEvent);
|
||||||
|
Assert.IsTrue(reduced.TargetWeight is null || reduced.TargetWeight <= c.Target, reduced.ToString());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheCodeCallsNoWithdrawalOrTransferEndpoint()
|
||||||
|
{
|
||||||
|
// SPEC 9.1 point 2: OKX withdrawals and transfers, Alpaca transfers and bank links, in any form.
|
||||||
|
var endpoint = new System.Text.RegularExpressions.Regex(@"asset/withdrawal|asset/transfer|/transfers\b|ach_relationships|recipient_banks|/withdraw",
|
||||||
|
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||||
|
var offenders = Repo.Files()
|
||||||
|
.Where(f => f.Extension == ".cs" && Repo.Relative(f).StartsWith("src", StringComparison.Ordinal))
|
||||||
|
.Where(f => endpoint.IsMatch(File.ReadAllText(f.FullName)))
|
||||||
|
.Select(Repo.Relative)
|
||||||
|
.ToList();
|
||||||
|
Assert.IsEmpty(offenders, string.Join(", ", offenders));
|
||||||
|
Assert.IsTrue(Repo.Files().Count(f => f.Extension == ".cs" && Repo.Relative(f).StartsWith("src", StringComparison.Ordinal)) > 50, "the scan sees the code");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 9.2: the monitor of losses ----
|
||||||
|
|
||||||
|
private static List<IndexPoint> Points(params (double HoursAgo, decimal Index)[] points) =>
|
||||||
|
[.. points.Select(p => new IndexPoint(_now - TimeSpan.FromHours(p.HoursAgo), p.Index)).OrderBy(p => p.At)];
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheDayStartsAtMidnightInItaly()
|
||||||
|
{
|
||||||
|
Assert.AreEqual(new DateTimeOffset(2026, 11, 10, 23, 0, 0, TimeSpan.Zero), RiskMonitor.ItalianMidnight(_now));
|
||||||
|
Assert.AreEqual(new DateTimeOffset(2026, 7, 10, 22, 0, 0, TimeSpan.Zero), RiskMonitor.ItalianMidnight(new DateTimeOffset(2026, 7, 11, 8, 0, 0, TimeSpan.Zero)));
|
||||||
|
|
||||||
|
// A fall at 23:30 in Rome of the day before belongs to yesterday.
|
||||||
|
var m = RiskMeasures.From(Points((24, 1.00m), (11.5, 0.97m), (0, 0.97m)), _now, null);
|
||||||
|
Assert.AreEqual(0m, m.DayChange);
|
||||||
|
Assert.AreEqual(-0.03m, m.Drawdown);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void ALossOfTwoPercentInADayBlocksEntriesForTwentyFourHours()
|
||||||
|
{
|
||||||
|
var m = RiskMeasures.From(Points((12, 1.00m), (0, 0.975m)), _now, null);
|
||||||
|
var reading = RiskMonitor.Step(RiskMonitorState.Initial, m, _now, _limits);
|
||||||
|
Assert.AreEqual(_now + TimeSpan.FromHours(24), reading.State.DailyBlockUntil);
|
||||||
|
Assert.IsTrue(reading.Alerts.Any(a => a.Kind == RiskAlertKinds.DailyLoss));
|
||||||
|
Assert.IsTrue(RiskMonitor.EntriesBlocked(reading.State, _now + TimeSpan.FromHours(23)), "24 hours, not until midnight");
|
||||||
|
Assert.IsFalse(RiskMonitor.EntriesBlocked(reading.State, _now + TimeSpan.FromHours(25)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void ALossOfFivePercentInAWeekHalvesRiskForSevenDays()
|
||||||
|
{
|
||||||
|
var m = RiskMeasures.From(Points((24 * 7.5, 1.00m), (24 * 6, 0.96m), (12, 0.95m), (0, 0.948m)), _now, null);
|
||||||
|
Assert.IsTrue(m.WeekChange <= -0.05m);
|
||||||
|
var reading = RiskMonitor.Step(RiskMonitorState.Initial, m, _now, _limits);
|
||||||
|
Assert.IsNull(reading.State.DailyBlockUntil);
|
||||||
|
Assert.AreEqual(0.5m, RiskMonitor.Multiplier(reading.State, RiskMeasures.None, _now + TimeSpan.FromDays(6), _limits));
|
||||||
|
Assert.AreEqual(1m, RiskMonitor.Multiplier(reading.State, RiskMeasures.None, _now + TimeSpan.FromDays(7.1), _limits));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheFallFromTheHighHalvesAtTenAndTripsTheSwitchAtFifteen()
|
||||||
|
{
|
||||||
|
var half = RiskMonitor.Step(RiskMonitorState.Initial, new RiskMeasures(0m, 0m, -0.11m), _now, _limits);
|
||||||
|
Assert.AreEqual(0.5m, RiskMonitor.Multiplier(half.State, half.Measures, _now, _limits));
|
||||||
|
Assert.IsFalse(half.State.Tripped);
|
||||||
|
Assert.AreEqual(1, half.Alerts.Count(a => a.Kind == RiskAlertKinds.DrawdownHalf));
|
||||||
|
Assert.AreEqual(0, RiskMonitor.Step(half.State, half.Measures, _now, _limits).Alerts.Count(a => a.Kind == RiskAlertKinds.DrawdownHalf), "said once");
|
||||||
|
|
||||||
|
var stop = RiskMonitor.Step(half.State, new RiskMeasures(0m, 0m, -0.16m), _now, _limits);
|
||||||
|
Assert.IsTrue(stop.State.Tripped);
|
||||||
|
Assert.IsTrue(RiskMonitor.EntriesBlocked(stop.State, _now + TimeSpan.FromDays(30)), "only the user restarts it");
|
||||||
|
Assert.AreEqual(RiskSeverities.Critical, stop.Alerts.Single(a => a.Kind == RiskAlertKinds.DrawdownStop).Severity);
|
||||||
|
|
||||||
|
// With the week's halving too the purchases are a quarter.
|
||||||
|
var both = half.State with { WeeklyHalvingUntil = _now + TimeSpan.FromDays(3) };
|
||||||
|
Assert.AreEqual(0.25m, RiskMonitor.Multiplier(both, half.Measures, _now, _limits));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void AtEightyPercentOfAThresholdOneWarningAndNoBlock()
|
||||||
|
{
|
||||||
|
var near = new RiskMeasures(-0.017m, 0m, -0.017m);
|
||||||
|
var first = RiskMonitor.Step(RiskMonitorState.Initial, near, _now, _limits);
|
||||||
|
Assert.AreEqual(1, first.Alerts.Count(a => a.Kind == RiskAlertKinds.Warning), "the day's loss; the fall is far from 8%");
|
||||||
|
Assert.IsFalse(RiskMonitor.EntriesBlocked(first.State, _now));
|
||||||
|
Assert.AreEqual(1m, RiskMonitor.Multiplier(first.State, near, _now, _limits));
|
||||||
|
Assert.AreEqual(0, RiskMonitor.Step(first.State, near, _now, _limits).Alerts.Count, "one for each crossing");
|
||||||
|
|
||||||
|
var back = RiskMonitor.Step(first.State, RiskMeasures.None, _now, _limits);
|
||||||
|
Assert.AreEqual(1, RiskMonitor.Step(back.State, near, _now, _limits).Alerts.Count, "a new crossing warns again");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void ARestartAfterATripMeasuresTheHighFromNow()
|
||||||
|
{
|
||||||
|
var series = Points((48, 1.00m), (0, 0.84m));
|
||||||
|
var tripped = RiskMonitor.Step(RiskMonitorState.Initial, RiskMeasures.From(series, _now, null), _now, _limits).State;
|
||||||
|
Assert.IsTrue(tripped.Tripped);
|
||||||
|
Assert.AreEqual(1.00m, tripped.Peak);
|
||||||
|
|
||||||
|
var restarted = RiskMonitor.Restart(tripped, _now);
|
||||||
|
Assert.IsFalse(restarted.Tripped);
|
||||||
|
Assert.IsNull(restarted.Peak);
|
||||||
|
var later = _now + TimeSpan.FromHours(1);
|
||||||
|
var after = RiskMeasures.From([.. series, new IndexPoint(later, 0.84m)], later, restarted.PeakFrom, restarted.Peak);
|
||||||
|
Assert.AreEqual(0m, after.Drawdown, "otherwise the switch would trip again at once");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheHighIsRememberedBeyondTheSeriesRead() =>
|
||||||
|
Assert.AreEqual(Math.Round((1.0m / 1.2m) - 1m, 6), Math.Round(RiskMeasures.From(Points((1, 1.0m), (0, 1.0m)), _now, null, knownPeak: 1.2m).Drawdown, 6));
|
||||||
|
|
||||||
|
// ---- 9.2: technical checks ----
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TechnicalChecksStopEntriesOnOldPricesFarLimitsAndAWrongClock()
|
||||||
|
{
|
||||||
|
Assert.IsNull(RiskRules.TechnicalRefusal(_now, _now - TimeSpan.FromSeconds(59), 100m, 100.9m, TimeSpan.FromSeconds(1), _limits));
|
||||||
|
Assert.AreEqual(RiskReasons.StalePrice, RiskRules.TechnicalRefusal(_now, _now - TimeSpan.FromSeconds(61), 100m, null, null, _limits));
|
||||||
|
Assert.AreEqual(RiskReasons.StalePrice, RiskRules.TechnicalRefusal(_now, null, null, null, null, _limits));
|
||||||
|
Assert.AreEqual(RiskReasons.PriceGap, RiskRules.TechnicalRefusal(_now, _now, 100m, 101.5m, null, _limits));
|
||||||
|
Assert.AreEqual(RiskReasons.ClockSkew, RiskRules.TechnicalRefusal(_now, _now, 100m, null, TimeSpan.FromSeconds(-3), _limits));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Settings of the limits ----
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void LimitsComeFromSettingsAndRaisingOneIsRecognised()
|
||||||
|
{
|
||||||
|
var values = RiskSettings.Limits.ToDictionary(d => d.Key, d => d.Default);
|
||||||
|
Assert.AreEqual(RiskLimits.Default, RiskSettings.From(k => values[k]));
|
||||||
|
values[RiskSettings.DailyLoss.Key] = "3";
|
||||||
|
var looser = RiskSettings.From(k => values[k]);
|
||||||
|
Assert.AreEqual(0.03m, looser.DailyLoss);
|
||||||
|
Assert.IsTrue(RiskLimits.Default.RaisedBy(looser));
|
||||||
|
Assert.IsFalse(looser.RaisedBy(RiskLimits.Default), "lowering a limit needs no confirmation");
|
||||||
|
Assert.IsNotNull(RiskSettings.DailyLoss.Check!("50"));
|
||||||
|
Assert.AreEqual("off", RiskSettings.PdtGuard.Default, "the day-trade guard is off by default");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 9.5: scenarios ----
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void ScenariosWithAndWithoutStops()
|
||||||
|
{
|
||||||
|
var positions = new[]
|
||||||
|
{
|
||||||
|
new ScenarioPosition(true, 2_000m, 1_800m),
|
||||||
|
new ScenarioPosition(false, 3_000m, 2_700m),
|
||||||
|
new ScenarioPosition(false, 1_000m, null),
|
||||||
|
};
|
||||||
|
var result = Scenarios.Compute(Scenarios.Default, positions, dollarAccountEur: 4_000m, equityEur: 10_000m);
|
||||||
|
Assert.AreEqual(-400m, result[0].WithoutStops);
|
||||||
|
Assert.AreEqual(-0.04m, result[0].WithoutStopsShare);
|
||||||
|
Assert.AreEqual(-200m, result[0].WithStops, "the stop limits the loss");
|
||||||
|
Assert.AreEqual(-280m, result[1].WithoutStops);
|
||||||
|
Assert.AreEqual(-280m, result[1].WithStops, "a 7% fall stays above the stop; without a stop the whole loss");
|
||||||
|
Assert.AreEqual(-680m, result[2].WithoutStops);
|
||||||
|
Assert.AreEqual(-200m, result[3].WithoutStops);
|
||||||
|
Assert.IsTrue(result[3].SameWithStops);
|
||||||
|
Assert.IsNull(result[3].WithStops, "stops do not reduce the dollar");
|
||||||
|
|
||||||
|
// Rounded to 5 euro.
|
||||||
|
Assert.AreEqual(-25m, Scenarios.Compute([new("x", -0.2m, 0m, 0m)], [new ScenarioPosition(true, 113m, null)], 0m, 1_000m)[0].WithStops);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void ScenariosAreASettingTheUserCanWrite()
|
||||||
|
{
|
||||||
|
CollectionAssert.AreEqual(Scenarios.Default.ToList(), Scenarios.Parse(Scenarios.Setting.Default).ToList(), "round trip");
|
||||||
|
Assert.AreEqual(Scenarios.Default.Count, Scenarios.Parse(Scenarios.Setting.Default).Count);
|
||||||
|
var custom = Scenarios.Parse("Crollo; −30; −10,5; 0");
|
||||||
|
Assert.AreEqual(-0.105m, custom[0].Stocks);
|
||||||
|
Assert.IsNotNull(Scenarios.Setting.Check!("solo testo"));
|
||||||
|
Assert.IsNotNull(Scenarios.Setting.Check!("x; -200; 0; 0"));
|
||||||
|
Assert.IsNull(Scenarios.Setting.Check!(Scenarios.Setting.Default));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 8.5: correctives ----
|
||||||
|
|
||||||
|
private static CalendarEvent Event(string kind, DateTimeOffset at, string impact = "High", string currency = "USD") =>
|
||||||
|
new(kind, "evento", at, true, "test", kind + at.ToString("O", System.Globalization.CultureInfo.InvariantCulture)) { Currency = currency, Impact = impact };
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheCalendarBlocksAroundImportantEvents()
|
||||||
|
{
|
||||||
|
var cpi = Event(CalendarEventKinds.Economic, _now);
|
||||||
|
Assert.AreEqual((_now - TimeSpan.FromMinutes(30), _now + TimeSpan.FromMinutes(30)), CalendarBlocks.Window(cpi));
|
||||||
|
Assert.IsNull(CalendarBlocks.Window(Event(CalendarEventKinds.Economic, _now, impact: "Medium")));
|
||||||
|
Assert.IsNull(CalendarBlocks.Window(Event(CalendarEventKinds.Economic, _now, currency: "EUR")));
|
||||||
|
Assert.AreEqual(_now + TimeSpan.FromMinutes(60), CalendarBlocks.Window(Event(CalendarEventKinds.CentralBank, _now, currency: "EUR"))!.Value.To);
|
||||||
|
|
||||||
|
// Two windows that overlap make one block; outside it the entry goes now.
|
||||||
|
var fed = Event(CalendarEventKinds.CentralBank, _now + TimeSpan.FromMinutes(45));
|
||||||
|
Assert.AreEqual(_now + TimeSpan.FromMinutes(105), CalendarBlocks.BlockedUntil(_now - TimeSpan.FromMinutes(10), [cpi, fed]));
|
||||||
|
Assert.IsNull(CalendarBlocks.BlockedUntil(_now - TimeSpan.FromHours(2), [cpi, fed]));
|
||||||
|
|
||||||
|
// Tried again at the end of the window, or dropped when the deadline comes first.
|
||||||
|
Assert.AreEqual(_now + TimeSpan.FromMinutes(30), CalendarBlocks.RetryAt(_now, [cpi], _now + TimeSpan.FromHours(1)));
|
||||||
|
Assert.IsNull(CalendarBlocks.RetryAt(_now, [cpi], _now + TimeSpan.FromMinutes(10)));
|
||||||
|
Assert.AreEqual(new DateTimeOffset(2026, 11, 11, 12, 0, 0, TimeSpan.Zero), CalendarBlocks.CryptoDeadline(_now));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheCalendarStageTurnsEntriesIntoNothingButKeepsStops()
|
||||||
|
{
|
||||||
|
var bars = StrategyData.Series(StrategyData.FromCloses([100, 100, 100]));
|
||||||
|
var holdings = new Dictionary<string, Holding> { ["AAA"] = new(10m, 100m, 90m, StrategyData.Start) };
|
||||||
|
var context = new StrategyContext(StrategyData.Start.AddDays(2), _now, ["AAA", "BBB"], new PortfolioView(9_000m, 10_000m, holdings), _ => bars, _ => null);
|
||||||
|
var stage = new CalendarStage(_ => [Event(CalendarEventKinds.Economic, _now)]);
|
||||||
|
var result = stage.Apply(context, [new Intent("AAA", 0.3m, "more") { Stop = 92m }, new Intent("BBB", 0.1m, "new") { Stop = 90m }, new Intent("CCC", 0m, "exit")]);
|
||||||
|
Assert.IsNull(result[0].TargetWeight);
|
||||||
|
Assert.AreEqual(92m, result[0].Stop, "the stop of a held position still follows the strategy");
|
||||||
|
Assert.IsNull(result[1].TargetWeight);
|
||||||
|
Assert.IsNull(result[1].Stop);
|
||||||
|
CollectionAssert.Contains(result[1].Adjustments.ToList(), CorrectiveReasons.CalendarEvent);
|
||||||
|
Assert.AreEqual(0m, result[2].TargetWeight, "exits pass");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheCryptoRegimeIsRiskyBelowTheAverageOrWithHighVolatility()
|
||||||
|
{
|
||||||
|
var settings = new CryptoRegimeSettings();
|
||||||
|
Assert.IsNull(CryptoRegime.Risky(StrategyData.Series(StrategyData.SteadyRise(400)), settings));
|
||||||
|
|
||||||
|
var falling = StrategyData.FromCloses([.. Enumerable.Range(0, 260).Select(i => i < 230 ? 100.0 + i : 330.0 - (5 * (i - 229)))]);
|
||||||
|
Assert.AreEqual(CorrectiveReasons.CryptoRegimeAverage, CryptoRegime.Risky(StrategyData.Series(falling), settings));
|
||||||
|
|
||||||
|
// Calm for two years, then a week of large swings while the price stays above its average.
|
||||||
|
var closes = Enumerable.Range(0, 800).Select(i => 100.0 * Math.Pow(1.002, i) * (1 + (0.002 * (i % 2)))).ToList();
|
||||||
|
for (var i = 790; i < 800; i++)
|
||||||
|
{
|
||||||
|
closes[i] = closes[789] * (i % 2 == 0 ? 1.08 : 1.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual(CorrectiveReasons.CryptoRegimeVolatility, CryptoRegime.Risky(StrategyData.Series(StrategyData.FromCloses(closes)), settings));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- The risk engine inside the backtest ----
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void InTheBacktestAPositionTooHeavyComesBackToTheThreshold()
|
||||||
|
{
|
||||||
|
var bars = StrategyData.Series(StrategyData.FromCloses([100, 100, 100]));
|
||||||
|
var holdings = new Dictionary<string, Holding> { ["AAA"] = new(30m, 100m, 90m, StrategyData.Start) };
|
||||||
|
var day = StrategyData.Start.AddDays(2);
|
||||||
|
var context = new StrategyContext(day, BacktestRisk.At(day), ["AAA"], new PortfolioView(7_000m, 10_000m, holdings), _ => bars, _ => StrategyData.Share("AAA"))
|
||||||
|
{
|
||||||
|
History = [new EquityMark(day, 10_000m, 3_000m)],
|
||||||
|
};
|
||||||
|
var result = new BacktestRisk().Apply(context, []);
|
||||||
|
var cut = result.Single();
|
||||||
|
Assert.AreEqual("AAA", cut.Symbol);
|
||||||
|
Assert.AreEqual(0.2m, cut.TargetWeight);
|
||||||
|
CollectionAssert.Contains(cut.Adjustments.ToList(), RiskReasons.PositionLimit);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void InTheBacktestNewEntriesStopAfterADayOfLosses()
|
||||||
|
{
|
||||||
|
var bars = StrategyData.Series(StrategyData.FromCloses([100, 100, 100]));
|
||||||
|
var day = StrategyData.Start.AddDays(2);
|
||||||
|
var context = new StrategyContext(day, BacktestRisk.At(day), ["AAA"], new PortfolioView(9_700m, 9_700m, new Dictionary<string, Holding>()), _ => bars,
|
||||||
|
_ => StrategyData.Share("AAA"))
|
||||||
|
{
|
||||||
|
History = [new EquityMark(day.AddDays(-1), 10_000m, 0m), new EquityMark(day, 9_700m, 0m)],
|
||||||
|
};
|
||||||
|
var risk = new BacktestRisk();
|
||||||
|
var result = risk.Apply(context, [new Intent("AAA", 0.1m, "entry") { Stop = 95m }]);
|
||||||
|
Assert.IsNull(result[0].TargetWeight);
|
||||||
|
CollectionAssert.Contains(result[0].Adjustments.ToList(), RiskReasons.DailyLossBlock);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -147,18 +147,23 @@ public sealed class ServerTests
|
|||||||
[TestMethod]
|
[TestMethod]
|
||||||
public async Task ComputerOnlyModesRefuseForeignHostNames()
|
public async Task ComputerOnlyModesRefuseForeignHostNames()
|
||||||
{
|
{
|
||||||
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
|
// The server stops before its folder is deleted: on Windows an open database cannot be deleted.
|
||||||
var demoRoot = server.Host.Config.Data.Root;
|
string demoRoot;
|
||||||
using (var mine = await server.GetAsync("/api/me"))
|
|
||||||
{
|
{
|
||||||
Assert.AreEqual(HttpStatusCode.OK, mine.StatusCode);
|
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
|
||||||
|
demoRoot = server.Host.Config.Data.Root;
|
||||||
|
using (var mine = await server.GetAsync("/api/me"))
|
||||||
|
{
|
||||||
|
Assert.AreEqual(HttpStatusCode.OK, mine.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
// DNS rebinding: a page whose name now points at 127.0.0.1 arrives from the loopback with its own Host.
|
||||||
|
using var request = new HttpRequestMessage(HttpMethod.Get, new Uri("/api/me", UriKind.Relative));
|
||||||
|
request.Headers.Host = "evil.example:" + server.BaseAddress.Port.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||||
|
using var foreign = await server.Http.SendAsync(request);
|
||||||
|
Assert.AreEqual(HttpStatusCode.Forbidden, foreign.StatusCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
// DNS rebinding: a page whose name now points at 127.0.0.1 arrives from the loopback with its own Host.
|
|
||||||
using var request = new HttpRequestMessage(HttpMethod.Get, new Uri("/api/me", UriKind.Relative));
|
|
||||||
request.Headers.Host = "evil.example:" + server.BaseAddress.Port.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
|
||||||
using var foreign = await server.Http.SendAsync(request);
|
|
||||||
Assert.AreEqual(HttpStatusCode.Forbidden, foreign.StatusCode);
|
|
||||||
TempFolder.Delete(demoRoot);
|
TempFolder.Delete(demoRoot);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -368,34 +373,38 @@ public sealed class ServerTests
|
|||||||
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
|
Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools();
|
||||||
var before = Snapshot(configured);
|
var before = Snapshot(configured);
|
||||||
Assert.IsTrue(before.Keys.Any(k => k.EndsWith(".sqlite3", StringComparison.Ordinal)));
|
Assert.IsTrue(before.Keys.Any(k => k.EndsWith(".sqlite3", StringComparison.Ordinal)));
|
||||||
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), dataDir: configured, extraArgs: ["--demo"]);
|
// The server stops before its folder is deleted: on Windows an open database cannot be deleted.
|
||||||
|
string demoRoot;
|
||||||
// Its own folder under the temporary directory, the configured one untouched.
|
|
||||||
var demoRoot = server.Host.Config.Data.Root;
|
|
||||||
StringAssert.StartsWith(demoRoot, Path.Combine(Path.GetTempPath(), "anubis-demo"));
|
|
||||||
|
|
||||||
// Appendix F on screen, frozen clock, signed in by itself, the footer says it.
|
|
||||||
var html = await server.TextAsync("/");
|
|
||||||
StringAssert.Contains(html, "+412,46 €");
|
|
||||||
StringAssert.Contains(html, "Venerdì 9 ottobre 2026, ore 08:21");
|
|
||||||
StringAssert.Contains(html, "Sorveglio 10 posizioni, ognuna con il suo stop.");
|
|
||||||
StringAssert.Contains(html, "Modalità dimostrativa. Numeri, titoli e notizie sono dati di esempio.");
|
|
||||||
|
|
||||||
// The live status arrives over the WebSocket.
|
|
||||||
using var socket = new ClientWebSocket();
|
|
||||||
await socket.ConnectAsync(new Uri(server.BaseAddress.ToString().Replace("http", "ws", StringComparison.Ordinal) + "ws"), CancellationToken.None);
|
|
||||||
var buffer = new byte[4096];
|
|
||||||
var received = await socket.ReceiveAsync(buffer, CancellationToken.None);
|
|
||||||
var message = Encoding.UTF8.GetString(buffer, 0, received.Count);
|
|
||||||
StringAssert.Contains(message, "\"type\":\"status\"");
|
|
||||||
StringAssert.Contains(message, "\"bot\":\"active\"");
|
|
||||||
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);
|
|
||||||
|
|
||||||
var after = Snapshot(configured);
|
|
||||||
CollectionAssert.AreEquivalent(before.Keys.ToList(), after.Keys.ToList(), "No file added or removed in the configured data folder.");
|
|
||||||
foreach (var (name, hash) in before)
|
|
||||||
{
|
{
|
||||||
Assert.AreEqual(hash, after[name], name + " changed");
|
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), dataDir: configured, extraArgs: ["--demo"]);
|
||||||
|
|
||||||
|
// Its own folder under the temporary directory, the configured one untouched.
|
||||||
|
demoRoot = server.Host.Config.Data.Root;
|
||||||
|
StringAssert.StartsWith(demoRoot, Path.Combine(Path.GetTempPath(), "anubis-demo"));
|
||||||
|
|
||||||
|
// Appendix F on screen, frozen clock, signed in by itself, the footer says it.
|
||||||
|
var html = await server.TextAsync("/");
|
||||||
|
StringAssert.Contains(html, "+412,46 €");
|
||||||
|
StringAssert.Contains(html, "Venerdì 9 ottobre 2026, ore 08:21");
|
||||||
|
StringAssert.Contains(html, "Sorveglio 10 posizioni, ognuna con il suo stop.");
|
||||||
|
StringAssert.Contains(html, "Modalità dimostrativa. Numeri, titoli e notizie sono dati di esempio.");
|
||||||
|
|
||||||
|
// The live status arrives over the WebSocket.
|
||||||
|
using var socket = new ClientWebSocket();
|
||||||
|
await socket.ConnectAsync(new Uri(server.BaseAddress.ToString().Replace("http", "ws", StringComparison.Ordinal) + "ws"), CancellationToken.None);
|
||||||
|
var buffer = new byte[4096];
|
||||||
|
var received = await socket.ReceiveAsync(buffer, CancellationToken.None);
|
||||||
|
var message = Encoding.UTF8.GetString(buffer, 0, received.Count);
|
||||||
|
StringAssert.Contains(message, "\"type\":\"status\"");
|
||||||
|
StringAssert.Contains(message, "\"bot\":\"active\"");
|
||||||
|
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);
|
||||||
|
|
||||||
|
var after = Snapshot(configured);
|
||||||
|
CollectionAssert.AreEquivalent(before.Keys.ToList(), after.Keys.ToList(), "No file added or removed in the configured data folder.");
|
||||||
|
foreach (var (name, hash) in before)
|
||||||
|
{
|
||||||
|
Assert.AreEqual(hash, after[name], name + " changed");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
TempFolder.Delete(demoRoot);
|
TempFolder.Delete(demoRoot);
|
||||||
|
|||||||
@@ -293,4 +293,25 @@ public sealed class AccessTests
|
|||||||
var history = await new SettingsStore(test.Db, clock, new EventBus()).HistoryAsync().ConfigureAwait(false);
|
var history = await new SettingsStore(test.Db, clock, new EventBus()).HistoryAsync().ConfigureAwait(false);
|
||||||
CollectionAssert.IsSubsetOf(new[] { "security.password", "security.second_factor" }, history.Select(h => h.Key).Distinct().ToList());
|
CollectionAssert.IsSubsetOf(new[] { "security.password", "security.second_factor" }, history.Select(h => h.Key).Distinct().ToList());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task TheFreshPasswordOfTheProcedureStopsAfterFiveWrongAttempts()
|
||||||
|
{
|
||||||
|
// SPEC 12.4: a stolen session must not be able to try passwords on the confirmation forms.
|
||||||
|
var clock = new ManualClock(new DateTimeOffset(2026, 11, 11, 9, 0, 0, TimeSpan.Zero));
|
||||||
|
await using var test = await DatabaseTests.MigratedAsync().ConfigureAwait(false);
|
||||||
|
var access = new AccessStore(test.Db, clock, new SecretStore(test.Db, clock, new byte[32]), iterations: 1000);
|
||||||
|
Assert.IsTrue(await access.EnsureUserAsync("password-giusta", mustChange: false).ConfigureAwait(false));
|
||||||
|
Assert.IsTrue(await access.ReauthenticateAsync("password-giusta", null).ConfigureAwait(false));
|
||||||
|
|
||||||
|
for (var i = 0; i < LoginLimiter.PerAddress; i++)
|
||||||
|
{
|
||||||
|
Assert.IsFalse(await access.ReauthenticateAsync("sbagliata-" + i, null).ConfigureAwait(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsFalse(await access.ReauthenticateAsync("password-giusta", null).ConfigureAwait(false), "even the right password waits");
|
||||||
|
clock.Advance(LoginLimiter.Window);
|
||||||
|
Assert.IsTrue(await access.ReauthenticateAsync("password-giusta", null).ConfigureAwait(false));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,207 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using Anubis.Core;
|
||||||
|
using Anubis.Db;
|
||||||
|
using Anubis.Risk;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The Operazioni, Strategie and Rischio screens and the risk part of Impostazioni (issue #45; mockups 03, 04, 07).
|
||||||
|
/// </summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class StrategyScreensTests
|
||||||
|
{
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task TheDemoShowsTradesStrategiesAndRiskAsInTheMockups()
|
||||||
|
{
|
||||||
|
var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]);
|
||||||
|
var demoRoot = server.Host.Config.Data.Root;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// Mockup 03: the balance of the 41 trades of appendix F, and the "why" of each from the decisions.
|
||||||
|
var trades = await server.TextAsync("/operazioni");
|
||||||
|
foreach (var text in new[]
|
||||||
|
{
|
||||||
|
"1,62", "+239,27", "22 su 41", "53,7%", "+28,42", "20,31", "14,82", "Mostrate 20 di 41", "Tornata sopra la media a 5 giorni",
|
||||||
|
"Perché l'ho comprata", "Tutti i limiti di rischio rispettati", "Stop di protezione raggiunto",
|
||||||
|
})
|
||||||
|
{
|
||||||
|
StringAssert.Contains(trades, text, $"Missing {text} on Operazioni.");
|
||||||
|
}
|
||||||
|
|
||||||
|
StringAssert.Contains(await server.TextAsync("/operazioni?esito=perdite"), "Mostrate 19 di 19");
|
||||||
|
using (var csv = await server.GetAsync("/api/operazioni.csv"))
|
||||||
|
{
|
||||||
|
Assert.AreEqual(HttpStatusCode.OK, csv.StatusCode);
|
||||||
|
Assert.AreEqual("text/csv", csv.Content.Headers.ContentType?.MediaType);
|
||||||
|
var lines = System.Text.Encoding.UTF8.GetString((await csv.Content.ReadAsByteArrayAsync())[3..]).Split('\n', StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
Assert.HasCount(42, lines, "a header and the 41 trades");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mockup 04: the four stages, 58 days of 60, the same result as on Conti.
|
||||||
|
var strategies = await server.TextAsync("/strategie");
|
||||||
|
foreach (var text in new[] { "Il percorso verso i soldi veri", "Reale ridotto", "3 strategie", "+231,60", "Giorni in simulazione", "58", "Disponibile tra 2 giorni" })
|
||||||
|
{
|
||||||
|
StringAssert.Contains(strategies, text, $"Missing {text} on Strategie.");
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsFalse(strategies.Contains("/azioni/strategie/", StringComparison.Ordinal), "The demo changes no stage.");
|
||||||
|
|
||||||
|
// Mockup 07: no block, the limits with their use, the worst fall of the demo, the scenarios.
|
||||||
|
var risk = await server.TextAsync("/rischio");
|
||||||
|
foreach (var text in new[] { "Nessun blocco attivo", "64,1%", "2,82% il 5 set", "Se succedesse domani", "465", "Cosa il bot non può fare, mai" })
|
||||||
|
{
|
||||||
|
StringAssert.Contains(risk, text, $"Missing {text} on Rischio.");
|
||||||
|
}
|
||||||
|
|
||||||
|
var settings = await server.TextAsync("/impostazioni");
|
||||||
|
StringAssert.Contains(settings, "Perdita in un giorno (%)");
|
||||||
|
Assert.IsFalse(settings.Contains("/azioni/rischio/limiti", StringComparison.Ordinal), "No risk form in the demo.");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
// The server first: on Windows a database still open cannot be deleted.
|
||||||
|
await server.DisposeAsync();
|
||||||
|
TempFolder.Delete(demoRoot);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task AStrategyThatFailedItsBacktestCannotEnterTheSimulation()
|
||||||
|
{
|
||||||
|
var network = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound));
|
||||||
|
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network, trading: true);
|
||||||
|
await server.SignInFirstTimeAsync();
|
||||||
|
|
||||||
|
// The outcome file of crypto_trend says "not passed"; the stock ones wait for the Alpaca keys.
|
||||||
|
var page = await server.TextAsync("/strategie");
|
||||||
|
StringAssert.Contains(page, "Non supera i test");
|
||||||
|
StringAssert.Contains(page, "In attesa dei dati");
|
||||||
|
Assert.IsFalse(page.Contains("/azioni/strategie/crypto_trend/simulazione", StringComparison.Ordinal), "No button for a strategy that did not pass.");
|
||||||
|
|
||||||
|
using var refused = await server.PostFormAsync("/strategie", "/azioni/strategie/crypto_trend/simulazione");
|
||||||
|
Assert.AreEqual("/strategie?errore=backtest", ServerHarness.Location(refused));
|
||||||
|
Assert.AreEqual(StrategyStages.Observation, (await server.Host.Services!.Trading!.Stages.GetAsync(StrategyNames.CryptoTrend, CancellationToken.None))!.Stage);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task LimitsGoDownFreelyAndUpOnlyWithThePhraseWhileAStrategyUsesRealMoney()
|
||||||
|
{
|
||||||
|
var network = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound));
|
||||||
|
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network, trading: true);
|
||||||
|
var password = await server.SignInFirstTimeAsync();
|
||||||
|
var services = server.Host.Services!;
|
||||||
|
var daily = RiskSettings.DailyLoss.Key;
|
||||||
|
|
||||||
|
// Not through the API: there the order of the limits and the procedure of SPEC 12.4 would be skipped.
|
||||||
|
var csrf = await server.Http.GetFromJsonAsync<Dictionary<string, string>>(new Uri("/api/antiforgery", UriKind.Relative));
|
||||||
|
using (var request = new HttpRequestMessage(HttpMethod.Put, new Uri("/api/settings/" + RiskSettings.DrawdownStop.Key, UriKind.Relative)) { Content = JsonContent.Create(new { value = "40" }) })
|
||||||
|
{
|
||||||
|
request.Headers.Add(csrf!["header"], csrf["token"]);
|
||||||
|
using var put = await server.Http.SendAsync(request);
|
||||||
|
Assert.AreEqual(HttpStatusCode.BadRequest, put.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual("15", (await services.Settings.GetAsync(RiskSettings.DrawdownStop.Key, CancellationToken.None)).Value);
|
||||||
|
|
||||||
|
// Out of range, or the halving after the switch: nothing changes.
|
||||||
|
using (var wrong = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "50")))
|
||||||
|
{
|
||||||
|
Assert.AreEqual("/impostazioni?errore=limite#rischio", ServerHarness.Location(wrong));
|
||||||
|
}
|
||||||
|
|
||||||
|
using (var order = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (RiskSettings.DrawdownHalf.Key, "20")))
|
||||||
|
{
|
||||||
|
Assert.AreEqual("/impostazioni?errore=ordine-limiti#rischio", ServerHarness.Location(order));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lower is always allowed.
|
||||||
|
using (var lower = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "1,5")))
|
||||||
|
{
|
||||||
|
Assert.AreEqual("/impostazioni?ok=limiti#rischio", ServerHarness.Location(lower));
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual("1.5", (await services.Settings.GetAsync(daily, CancellationToken.None)).Value);
|
||||||
|
|
||||||
|
// A strategy with real money: raising needs the phrase and the password, and the form asks for them.
|
||||||
|
await services.Db.WriteAsync(s => s.ExecuteAsync("UPDATE strategy_state SET stage = 'reduced' WHERE strategy = @s", CancellationToken.None,
|
||||||
|
("s", StrategyNames.CryptoTrend)), CancellationToken.None);
|
||||||
|
StringAssert.Contains(await server.TextAsync("/impostazioni"), StageBook.RaisePhrase);
|
||||||
|
using (var bare = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "2")))
|
||||||
|
{
|
||||||
|
Assert.AreEqual("/impostazioni?errore=frase-rischio#rischio", ServerHarness.Location(bare));
|
||||||
|
}
|
||||||
|
|
||||||
|
using (var badPassword = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "2"), ("frase", StageBook.RaisePhrase), ("password", "not-it")))
|
||||||
|
{
|
||||||
|
Assert.AreEqual("/impostazioni?errore=password-rischio#rischio", ServerHarness.Location(badPassword));
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual("1.5", (await services.Settings.GetAsync(daily, CancellationToken.None)).Value, "Refused raises change nothing.");
|
||||||
|
using (var confirmed = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "2"), ("frase", StageBook.RaisePhrase), ("password", password)))
|
||||||
|
{
|
||||||
|
Assert.AreEqual("/impostazioni?ok=limiti#rischio", ServerHarness.Location(confirmed));
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual("2", (await services.Settings.GetAsync(daily, CancellationToken.None)).Value);
|
||||||
|
|
||||||
|
// Lowering again needs nothing, even now.
|
||||||
|
using var lowerAgain = await server.PostFormAsync("/impostazioni", "/azioni/rischio/limiti", (daily, "1"));
|
||||||
|
Assert.AreEqual("/impostazioni?ok=limiti#rischio", ServerHarness.Location(lowerAgain));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Integration)]
|
||||||
|
public async Task StopCloseAndRestartGoThroughTheRiskEngine()
|
||||||
|
{
|
||||||
|
var network = new FakeHttp().On(_ => true, _ => FakeHttp.Respond("not here", HttpStatusCode.NotFound));
|
||||||
|
await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), marketHttp: network, trading: true);
|
||||||
|
await server.SignInFirstTimeAsync();
|
||||||
|
var services = server.Host.Services!;
|
||||||
|
async Task<string> StateAsync() => (await services.Settings.GetAsync(SettingsStore.BotState.Key, CancellationToken.None)).Value;
|
||||||
|
|
||||||
|
using (var stop = await server.PostFormAsync("/rischio", "/azioni/bot/ferma", ("ritorno", "/rischio")))
|
||||||
|
{
|
||||||
|
StringAssert.StartsWith(ServerHarness.Location(stop), "/rischio");
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual("stopped", await StateAsync());
|
||||||
|
StringAssert.Contains(await server.TextAsync("/rischio"), "Riparti");
|
||||||
|
|
||||||
|
// With the STOP file in the data folder the restart is refused.
|
||||||
|
var stopFile = services.Trading!.Risk!.StopFile!;
|
||||||
|
await File.WriteAllTextAsync(stopFile, "");
|
||||||
|
using (var refused = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva", ("ritorno", "/rischio")))
|
||||||
|
{
|
||||||
|
StringAssert.Contains(ServerHarness.Location(refused), "errore=file-stop");
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual("stopped", await StateAsync());
|
||||||
|
File.Delete(stopFile);
|
||||||
|
using (var restart = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva", ("ritorno", "/rischio")))
|
||||||
|
{
|
||||||
|
Assert.IsFalse(ServerHarness.Location(restart).Contains("errore", StringComparison.Ordinal), ServerHarness.Location(restart));
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual("active", await StateAsync());
|
||||||
|
|
||||||
|
// The switch tripped by itself in the simulation: the bot stays "active" elsewhere, and the page offers the restart.
|
||||||
|
await services.Db.WriteAsync(s => s.ExecuteAsync("INSERT INTO risk_state (id, world, state, created_at, updated_at) VALUES (@id, 'simulated', @j, @t, @t)",
|
||||||
|
CancellationToken.None, ("id", Guid.NewGuid()), ("j", new DbJson("{\"tripped\":true}")), ("t", DateTimeOffset.UtcNow)), CancellationToken.None);
|
||||||
|
var page = await server.TextAsync("/rischio");
|
||||||
|
StringAssert.Contains(page, "Interruttore scattato nel mondo simulato");
|
||||||
|
StringAssert.Contains(page, "Riparti");
|
||||||
|
using (var again = await server.PostFormAsync("/rischio", "/azioni/bot/riattiva", ("ritorno", "/rischio")))
|
||||||
|
{
|
||||||
|
Assert.IsFalse(ServerHarness.Location(again).Contains("errore", StringComparison.Ordinal), ServerHarness.Location(again));
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsFalse(await services.Trading.Risk.AnyTrippedAsync(CancellationToken.None));
|
||||||
|
Assert.AreEqual("active", await StateAsync());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,562 @@
|
|||||||
|
using Anubis.Backtest;
|
||||||
|
using Anubis.Data;
|
||||||
|
using Anubis.Strategies;
|
||||||
|
using Anubis.Trading;
|
||||||
|
|
||||||
|
namespace Anubis.Tests;
|
||||||
|
|
||||||
|
internal static class StrategyData
|
||||||
|
{
|
||||||
|
public static readonly DateOnly Start = new(2024, 1, 1);
|
||||||
|
|
||||||
|
public static InstrumentSpec Coin(string coin) => new(Venues.Okx, coin + "-EUR", coin, AssetClasses.Crypto, "EUR")
|
||||||
|
{
|
||||||
|
BaseCurrency = coin,
|
||||||
|
TickSize = 0.0001m,
|
||||||
|
LotSize = 0.00000001m,
|
||||||
|
MinSize = 0.00000001m,
|
||||||
|
MinNotional = 1m,
|
||||||
|
Status = "live",
|
||||||
|
};
|
||||||
|
|
||||||
|
public static InstrumentSpec Share(string symbol) => new(Venues.Alpaca, symbol, symbol, AssetClasses.Equity, "USD")
|
||||||
|
{
|
||||||
|
Fractionable = true,
|
||||||
|
Status = "active",
|
||||||
|
Exchange = "NASDAQ",
|
||||||
|
TickSize = 0.01m,
|
||||||
|
LotSize = 0.000000001m,
|
||||||
|
MinNotional = 1m,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>Bars with the given closes on consecutive days; high and low a fixed distance around the close.</summary>
|
||||||
|
public static List<DailyBar> FromCloses(IReadOnlyList<double> closes, DateOnly? from = null, double range = 0, double volume = 10_000)
|
||||||
|
{
|
||||||
|
var day = from ?? Start;
|
||||||
|
return [.. closes.Select((c, i) => new DailyBar(day.AddDays(i), c, c + range, c - range, c, volume))];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Bars on business days (no weekends) from a Monday.</summary>
|
||||||
|
public static List<DailyBar> OnBusinessDays(IReadOnlyList<DailyBar> bars, DateOnly from)
|
||||||
|
{
|
||||||
|
var days = BusinessDays(from, bars.Count);
|
||||||
|
return [.. bars.Select((b, i) => b with { Day = days[i] })];
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<DateOnly> BusinessDays(DateOnly from, int count)
|
||||||
|
{
|
||||||
|
var result = new List<DateOnly>(count);
|
||||||
|
for (var d = from; result.Count < count; d = d.AddDays(1))
|
||||||
|
{
|
||||||
|
if (d.DayOfWeek is not (DayOfWeek.Saturday or DayOfWeek.Sunday))
|
||||||
|
{
|
||||||
|
result.Add(d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A steady rise with a tiny alternating wobble: every period of crypto_trend is on, volatility near 1%.</summary>
|
||||||
|
public static List<DailyBar> SteadyRise(int days, double start = 100, double volume = 10_000) =>
|
||||||
|
FromCloses([.. Enumerable.Range(0, days).Select(i => start * Math.Pow(1.001, i) * (1 + (0.0005 * (i % 2))))], volume: volume);
|
||||||
|
|
||||||
|
public static BarSeries Series(IReadOnlyList<DailyBar> bars, InstrumentSpec? spec = null) =>
|
||||||
|
new BacktestInstrument(spec ?? Coin("BTC"), bars).SeriesThrough(bars[^1].Day);
|
||||||
|
|
||||||
|
public static BacktestDataset Crypto(params (string Coin, IReadOnlyList<DailyBar> Bars)[] coins) =>
|
||||||
|
new(coins.Select(c => new BacktestInstrument(Coin(c.Coin), c.Bars)), "EUR");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Indicators and the three base strategies (issues #38, #39, #40; SPEC 8.1–8.3).</summary>
|
||||||
|
[TestClass]
|
||||||
|
public sealed class StrategyTests
|
||||||
|
{
|
||||||
|
// ---- Indicators, against values computed by hand ----
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void IndicatorsGiveTheValuesComputedByHand()
|
||||||
|
{
|
||||||
|
var closes = StrategyData.Series(StrategyData.FromCloses([1, 2, 3, 4, 5]));
|
||||||
|
Assert.AreEqual(4d, Indicators.Sma(closes, 3));
|
||||||
|
Assert.IsNull(Indicators.Sma(closes, 6));
|
||||||
|
|
||||||
|
// True ranges: max(11−9, |11−9|, |9−9|) = 2; max(3, |12−10|, |9−10|) = 3; max(4, |11−11|, |7−11|) = 4.
|
||||||
|
var bars = StrategyData.Series(
|
||||||
|
[
|
||||||
|
new DailyBar(StrategyData.Start, 9, 10, 8, 9, 1),
|
||||||
|
new DailyBar(StrategyData.Start.AddDays(1), 10, 11, 9, 10, 1),
|
||||||
|
new DailyBar(StrategyData.Start.AddDays(2), 11, 12, 9, 11, 1),
|
||||||
|
new DailyBar(StrategyData.Start.AddDays(3), 9, 11, 7, 8, 1),
|
||||||
|
]);
|
||||||
|
Assert.AreEqual(3d, Indicators.Atr(bars, 3));
|
||||||
|
Assert.AreEqual(3.5d, Indicators.Atr(bars, 2));
|
||||||
|
|
||||||
|
// RSI(2) on 10, 11, 10,5, 12: average gain 0,5 and loss 0,25 on the first two changes; then +1,5 gives
|
||||||
|
// gain (0,5 + 1,5) / 2 = 1 and loss 0,25 / 2 = 0,125: RS 8, RSI 100 − 100 / 9.
|
||||||
|
Assert.AreEqual(100 - (100 / 9d), Indicators.Rsi(StrategyData.Series(StrategyData.FromCloses([10, 11, 10.5, 12])), 2)!.Value, 1e-12);
|
||||||
|
|
||||||
|
// 121 / 100 − 1, skipping the last close.
|
||||||
|
Assert.AreEqual(0.21, Indicators.Momentum(StrategyData.Series(StrategyData.FromCloses([100, 110, 121, 133.1])), 2, 1)!.Value, 1e-12);
|
||||||
|
|
||||||
|
// Returns +10% and −10%: sample standard deviation √0,02, times √365.
|
||||||
|
Assert.AreEqual(Math.Sqrt(0.02) * Math.Sqrt(365), Indicators.Volatility(StrategyData.Series(StrategyData.FromCloses([100, 110, 99])), 2, 365)!.Value, 1e-12);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- crypto_trend ----
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void ThePeriodsTurnOnAtANewHighAndOffBelowYesterdaysStop()
|
||||||
|
{
|
||||||
|
// Periods 2 and 3, flat bars (high = low = close) so only the closes count.
|
||||||
|
var settings = new CryptoTrendSettings { Periods = [2, 3], MaxStop = 0.15 };
|
||||||
|
var bars = StrategyData.FromCloses([10, 10, 10, 12, 13, 12.4, 12.6]);
|
||||||
|
bars[6] = bars[6] with { Low = 12.0 };
|
||||||
|
var tracker = new TrendTracker();
|
||||||
|
|
||||||
|
// Day 3, close 12: both periods beat their previous highs (10); stops at the middle of the last N closes, 11.
|
||||||
|
tracker.Advance(StrategyData.Series(bars[..4]), settings);
|
||||||
|
CollectionAssert.AreEqual(new[] { true, true }, tracker.Active.ToArray());
|
||||||
|
Assert.AreEqual(1d, tracker.Ensemble);
|
||||||
|
Assert.AreEqual(11d, tracker.ServerStop);
|
||||||
|
|
||||||
|
// Day 4, close 13: stops rise to 12,5 and 11,5; the server stop is the lowest, 11,5.
|
||||||
|
tracker.Advance(StrategyData.Series(bars[..5]), settings);
|
||||||
|
Assert.AreEqual(11.5d, tracker.ServerStop);
|
||||||
|
|
||||||
|
// Day 5, close 12,4: below the 2-day stop of yesterday (12,5), so that period turns off; the 3-day one stays,
|
||||||
|
// its stop rising to the middle of 12, 13, 12,4 = 12,5. e = 0,5.
|
||||||
|
tracker.Advance(StrategyData.Series(bars[..6]), settings);
|
||||||
|
CollectionAssert.AreEqual(new[] { false, true }, tracker.Active.ToArray());
|
||||||
|
Assert.AreEqual(0.5d, tracker.Ensemble);
|
||||||
|
Assert.AreEqual(12.5d, tracker.ServerStop);
|
||||||
|
|
||||||
|
// Day 6: the low (12) touches the server stop during the day. Every period goes back to 0, and the close of
|
||||||
|
// 12,6 is not a new high for either: no stop, no position.
|
||||||
|
tracker.Advance(StrategyData.Series(bars), settings);
|
||||||
|
CollectionAssert.AreEqual(new[] { false, false }, tracker.Active.ToArray());
|
||||||
|
Assert.AreEqual(0d, tracker.Ensemble);
|
||||||
|
Assert.IsNull(tracker.ServerStop);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheServerStopRisesStaysWithin15PercentAndFallsOnlyWhenAPeriodTurnsOn()
|
||||||
|
{
|
||||||
|
var tracker = new TrendTracker();
|
||||||
|
|
||||||
|
// Never more than 15% below the close: the middle of 10 and 20 is 15, the cap 17.
|
||||||
|
tracker.Advance(StrategyData.Series(StrategyData.FromCloses([10, 10, 20])), new CryptoTrendSettings { Periods = [2] });
|
||||||
|
Assert.AreEqual(17d, tracker.ServerStop);
|
||||||
|
|
||||||
|
// With a loose cap: the 2-day period alone lifts the stop to 11, 13, 15; on day 5 the 5-day period turns on
|
||||||
|
// with its stop at the middle of 10…17 = 13,5, and the server stop comes down to it.
|
||||||
|
var loose = new CryptoTrendSettings { Periods = [2, 5], MaxStop = 0.5 };
|
||||||
|
var bars = StrategyData.FromCloses([10, 10, 12, 14, 16, 17]);
|
||||||
|
var stops = new List<double?>();
|
||||||
|
for (var n = 3; n <= bars.Count; n++)
|
||||||
|
{
|
||||||
|
stops.Add(new TrendTracker().Advance(StrategyData.Series(bars[..n]), loose).ServerStop);
|
||||||
|
}
|
||||||
|
|
||||||
|
CollectionAssert.AreEqual(new double?[] { 11, 13, 15, 13.5 }, stops);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void WalkingTheBarsOnceOrDayByDayGivesTheSameState()
|
||||||
|
{
|
||||||
|
var bars = BacktestData.Walk(700, 11, start: 30_000, volatility: 0.04);
|
||||||
|
var settings = new CryptoTrendSettings();
|
||||||
|
var once = new TrendTracker().Advance(StrategyData.Series(bars), settings);
|
||||||
|
var stepwise = new TrendTracker();
|
||||||
|
for (var n = 1; n <= bars.Count; n++)
|
||||||
|
{
|
||||||
|
stepwise.Advance(StrategyData.Series([.. bars.Take(n)]), settings);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.AreEqual(once.Ensemble, stepwise.Ensemble);
|
||||||
|
Assert.AreEqual(once.ServerStop, stepwise.ServerStop);
|
||||||
|
CollectionAssert.AreEqual(once.Active.ToArray(), stepwise.Active.ToArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void WeightsFollowTheCapsThenShrinkTogether()
|
||||||
|
{
|
||||||
|
// Six coins in a steady rise: e = 1 and a volatility near 1%, so every raw weight hits its cap. 35% for BTC
|
||||||
|
// and ETH, 20% for the others: 150% in all, so everything shrinks by 1,5.
|
||||||
|
var coins = new[] { "BTC", "ETH", "SOL", "ADA", "XRP", "DOT" };
|
||||||
|
var data = StrategyData.Crypto([.. coins.Select(c => (c, (IReadOnlyList<DailyBar>)StrategyData.SteadyRise(450)))]);
|
||||||
|
var last = data.Sessions[^1];
|
||||||
|
var decision = BacktestEngine.DecideOnce(new CryptoTrend(), data, PortfolioState.OnlyCash(10_000m), last);
|
||||||
|
var weights = decision.Proposed.ToDictionary(i => i.Symbol, i => i.TargetWeight);
|
||||||
|
Assert.AreEqual(0.233333m, weights["BTC-EUR"]);
|
||||||
|
Assert.AreEqual(0.233333m, weights["ETH-EUR"]);
|
||||||
|
foreach (var other in new[] { "SOL-EUR", "ADA-EUR", "XRP-EUR", "DOT-EUR" })
|
||||||
|
{
|
||||||
|
Assert.AreEqual(0.133333m, weights[other]);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.IsTrue(decision.Proposed.All(i => i.Reason == CryptoTrend.Reasons.Entry && i.Stop > 0m));
|
||||||
|
|
||||||
|
// Alone, bitcoin stops at its cap.
|
||||||
|
var alone = BacktestEngine.DecideOnce(new CryptoTrend(), StrategyData.Crypto(("BTC", StrategyData.SteadyRise(450))), PortfolioState.OnlyCash(10_000m), last);
|
||||||
|
Assert.AreEqual(0.35m, alone.Proposed.Single().TargetWeight);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void APositionIsResizedOnlyBeyondTheThresholds()
|
||||||
|
{
|
||||||
|
var bars = StrategyData.SteadyRise(450);
|
||||||
|
var data = StrategyData.Crypto(("BTC", bars));
|
||||||
|
var last = data.Sessions[^1];
|
||||||
|
var close = Math.Round((decimal)bars[^1].Close, 8);
|
||||||
|
|
||||||
|
IReadOnlyList<Intent> At(decimal weight)
|
||||||
|
{
|
||||||
|
var quantity = weight * 10_000m / close;
|
||||||
|
var state = new PortfolioState(10_000m - (quantity * close), new Dictionary<string, Holding> { ["BTC-EUR"] = new(quantity, close, null, StrategyData.Start) });
|
||||||
|
return BacktestEngine.DecideOnce(new CryptoTrend(), data, state, last).Proposed;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Target 35%. At 30% the gap (5 points) is within 20% of the target (7 points): only the stop moves.
|
||||||
|
var near = At(0.30m).Single();
|
||||||
|
Assert.IsNull(near.TargetWeight);
|
||||||
|
Assert.AreEqual(CryptoTrend.Reasons.StopMoved, near.Reason);
|
||||||
|
|
||||||
|
// At 25% the gap (10 points) is beyond both thresholds: back to 35%.
|
||||||
|
var far = At(0.25m).Single();
|
||||||
|
Assert.AreEqual(0.35m, far.TargetWeight);
|
||||||
|
Assert.AreEqual(CryptoTrend.Reasons.Increase, far.Reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheUniverseIsTheTopTenOnTheFirstOfTheMonthWithoutStablecoinsOrYoungCoins()
|
||||||
|
{
|
||||||
|
// Twelve coins with growing traded value, a stablecoin with the largest of all, a coin listed 200 days ago.
|
||||||
|
var instruments = new List<BacktestInstrument>();
|
||||||
|
for (var k = 1; k <= 12; k++)
|
||||||
|
{
|
||||||
|
instruments.Add(new BacktestInstrument(StrategyData.Coin("C" + k.ToString("00", System.Globalization.CultureInfo.InvariantCulture)), StrategyData.SteadyRise(450, volume: 10_000 * k)));
|
||||||
|
}
|
||||||
|
|
||||||
|
instruments.Add(new BacktestInstrument(StrategyData.Coin("USDC"), StrategyData.FromCloses([.. Enumerable.Repeat(1d, 450)], volume: 1e12)));
|
||||||
|
instruments.Add(new BacktestInstrument(StrategyData.Coin("NEW"), StrategyData.FromCloses([.. Enumerable.Repeat(100d, 200)], from: StrategyData.Start.AddDays(250), volume: 1e9)));
|
||||||
|
var data = new BacktestDataset(instruments, "EUR");
|
||||||
|
var strategy = new CryptoTrend();
|
||||||
|
var day = new DateOnly(2025, 3, 20);
|
||||||
|
UniverseContext Context(DateOnly d) => new(d, [.. data.Instruments.Select(i => i.Symbol)])
|
||||||
|
{
|
||||||
|
Bars = s => data[s]!.SeriesThrough(d),
|
||||||
|
Spec = s => data[s]?.Spec,
|
||||||
|
};
|
||||||
|
|
||||||
|
var universe = strategy.Universe(Context(day));
|
||||||
|
CollectionAssert.AreEqual(Enumerable.Range(3, 10).Reverse().Select(k => "C" + k.ToString("00", System.Globalization.CultureInfo.InvariantCulture) + "-EUR").ToList(), universe.ToList());
|
||||||
|
|
||||||
|
// Live, the spread is known: one too wide is out, and the 11th by value comes in.
|
||||||
|
var live = new CryptoTrend().Universe(Context(day) with { SpreadBp = s => s == "C12-EUR" ? 25 : 5 });
|
||||||
|
CollectionAssert.DoesNotContain(live.ToList(), "C12-EUR");
|
||||||
|
CollectionAssert.Contains(live.ToList(), "C02-EUR");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void ACoinThatLeftTheUniverseIsManagedButNeverBought()
|
||||||
|
{
|
||||||
|
// A young coin (not in the universe) held at 10% in a steady rise: its target would be its cap, 20%.
|
||||||
|
var data = StrategyData.Crypto(("BTC", StrategyData.SteadyRise(450)), ("NEW", StrategyData.SteadyRise(450).GetRange(150, 300)));
|
||||||
|
var last = data.Sessions[^1];
|
||||||
|
var close = Math.Round((decimal)data["NEW-EUR"]!.Bars[^1].Close, 8);
|
||||||
|
var quantity = 1_000m / close;
|
||||||
|
var state = new PortfolioState(9_000m, new Dictionary<string, Holding> { ["NEW-EUR"] = new(quantity, close, null, last.AddDays(-10)) });
|
||||||
|
var intents = BacktestEngine.DecideOnce(new CryptoTrend(), data, state, last).Proposed;
|
||||||
|
var coin = intents.Single(i => i.Symbol == "NEW-EUR");
|
||||||
|
Assert.IsNull(coin.TargetWeight, "No purchase for a coin out of the universe.");
|
||||||
|
Assert.IsNotNull(coin.Stop);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void CryptoTrendDecidesOnTheMidnightUtcClose()
|
||||||
|
{
|
||||||
|
// The day's bar opens and closes at 00:00 UTC (trap 23): the decision comes at the close, at midnight.
|
||||||
|
var times = new List<DateTimeOffset>();
|
||||||
|
var data = StrategyData.Crypto(("BTC", BacktestData.Walk(30, 3, from: StrategyData.Start)));
|
||||||
|
BacktestEngine.Run(new Recording(new CryptoTrend(), times), data);
|
||||||
|
Assert.HasCount(30, times);
|
||||||
|
for (var i = 0; i < times.Count; i++)
|
||||||
|
{
|
||||||
|
Assert.AreEqual(new DateTimeOffset(StrategyData.Start.AddDays(i + 1).ToDateTime(TimeOnly.MinValue), TimeSpan.Zero), times[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void CryptoTrendDoesNotLookAhead()
|
||||||
|
{
|
||||||
|
var data = StrategyData.Crypto(
|
||||||
|
("BTC", BacktestData.Walk(900, 21, start: 30_000, drift: 0.001, volatility: 0.035, from: StrategyData.Start)),
|
||||||
|
("ETH", BacktestData.Walk(900, 22, start: 2_000, drift: 0.0008, volatility: 0.045, from: StrategyData.Start)),
|
||||||
|
("SOL", BacktestData.Walk(900, 23, start: 50, drift: 0.0005, volatility: 0.06, from: StrategyData.Start)));
|
||||||
|
var result = LookAheadCheck.Run(_ => new CryptoTrend(new CryptoTrendSettings { MinAgeDays = 100, MinValue = 0 }), data);
|
||||||
|
Assert.IsTrue(result.Passed, string.Join("\n", result.Mismatches.Take(3)));
|
||||||
|
var run = BacktestEngine.Run(new CryptoTrend(new CryptoTrendSettings { MinAgeDays = 100, MinValue = 0 }), data);
|
||||||
|
Assert.IsGreaterThan(5, run.Fills.Count, "The check must look at a strategy that trades.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- equity_momentum ----
|
||||||
|
|
||||||
|
private static readonly DateOnly Monday = new(2022, 1, 3);
|
||||||
|
|
||||||
|
/// <summary>Thirty stocks with different drifts, SPY as data only, on business days.</summary>
|
||||||
|
private static BacktestDataset Stocks(int sessions, double spyDrift, int count = 30, ulong seed = 100)
|
||||||
|
{
|
||||||
|
var instruments = new List<BacktestInstrument>();
|
||||||
|
for (var k = 0; k < count; k++)
|
||||||
|
{
|
||||||
|
var bars = BacktestData.Walk(sessions, seed + (ulong)k, start: 50 + k, drift: 0.0002 * (k - 10), volatility: 0.015 + (0.0005 * k));
|
||||||
|
instruments.Add(new BacktestInstrument(StrategyData.Share("S" + k.ToString("00", System.Globalization.CultureInfo.InvariantCulture)),
|
||||||
|
StrategyData.OnBusinessDays([.. bars.Select(b => b with { Volume = 100_000 })], Monday)));
|
||||||
|
}
|
||||||
|
|
||||||
|
var spy = BacktestData.Walk(sessions, seed + 999, start: 400, drift: spyDrift, volatility: 0.008);
|
||||||
|
instruments.Add(new BacktestInstrument(StrategyData.Share("SPY") with { IsFund = true }, StrategyData.OnBusinessDays([.. spy], Monday)));
|
||||||
|
return new BacktestDataset(instruments, "USD", dataOnly: ["SPY"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void TheWeeklyReviewIsTheLastCloseBeforeANewWeek()
|
||||||
|
{
|
||||||
|
StrategyContext At(DateOnly day, DateOnly? next) => new(day, default, [], new PortfolioView(0m, 0m, new Dictionary<string, Holding>()), _ => BarSeries.Empty, _ => null)
|
||||||
|
{
|
||||||
|
NextSession = next,
|
||||||
|
};
|
||||||
|
|
||||||
|
var friday = new DateOnly(2026, 4, 3);
|
||||||
|
Assert.IsTrue(EquityMomentum.IsReview(At(friday, friday.AddDays(3))));
|
||||||
|
Assert.IsFalse(EquityMomentum.IsReview(At(friday.AddDays(-1), friday)));
|
||||||
|
// Good Friday closed: Thursday is the last session of the week.
|
||||||
|
Assert.IsTrue(EquityMomentum.IsReview(At(friday.AddDays(-1), friday.AddDays(3))));
|
||||||
|
// A Monday holiday: the review on Friday, orders on Tuesday.
|
||||||
|
Assert.IsTrue(EquityMomentum.IsReview(At(friday, friday.AddDays(4))));
|
||||||
|
Assert.IsFalse(EquityMomentum.IsReview(At(friday, null)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void MomentumBuysOnTheFirstSessionOfTheWeekOnlyWhileTheMarketRises()
|
||||||
|
{
|
||||||
|
var rising = BacktestEngine.Run(new EquityMomentum(), Stocks(520, 0.001));
|
||||||
|
var buys = rising.Fills.Where(f => f.Side == OrderSide.Buy && f.Reason == EquityMomentum.Reasons.Entry).ToList();
|
||||||
|
Assert.IsNotEmpty(buys);
|
||||||
|
// Every purchase at the open of the first session of its week (here always a Monday).
|
||||||
|
Assert.IsTrue(buys.All(f => f.Day.DayOfWeek == DayOfWeek.Monday), string.Join(", ", buys.Select(f => f.Day)));
|
||||||
|
Assert.IsFalse(rising.Fills.Any(f => f.Symbol == "SPY"), "SPY is data, never an instrument.");
|
||||||
|
|
||||||
|
// At most 12 positions, no target above the 15% cap.
|
||||||
|
var entries = rising.Decisions.SelectMany(d => d.Proposed).Where(i => i.TargetWeight > 0m).ToList();
|
||||||
|
Assert.IsTrue(entries.All(i => i.TargetWeight <= 0.15m));
|
||||||
|
Assert.IsTrue(rising.Decisions.All(d => d.Proposed.Count(i => i.Reason == EquityMomentum.Reasons.Entry) <= 12));
|
||||||
|
|
||||||
|
// SPY below its 200-day average: no purchase at all.
|
||||||
|
var falling = BacktestEngine.Run(new EquityMomentum(), Stocks(520, -0.002));
|
||||||
|
Assert.IsFalse(falling.Fills.Any(f => f.Side == OrderSide.Buy));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void MomentumStopsOnlyRise()
|
||||||
|
{
|
||||||
|
var run = BacktestEngine.Run(new EquityMomentum(), Stocks(520, 0.001));
|
||||||
|
var stops = run.Decisions.SelectMany(d => d.Proposed.Where(i => i.Reason == EquityMomentum.Reasons.StopMoved).Select(i => (d.Day, i.Symbol, Stop: i.Stop!.Value))).ToList();
|
||||||
|
Assert.IsNotEmpty(stops);
|
||||||
|
foreach (var group in stops.GroupBy(s => s.Symbol))
|
||||||
|
{
|
||||||
|
var list = group.OrderBy(s => s.Day).ToList();
|
||||||
|
for (var i = 1; i < list.Count; i++)
|
||||||
|
{
|
||||||
|
// A new holding period may start lower; within one, every move is up.
|
||||||
|
var exited = run.Fills.Any(f => f.Symbol == group.Key && f.Side == OrderSide.Sell && f.Day > list[i - 1].Day && f.Day <= list[i].Day);
|
||||||
|
Assert.IsTrue(exited || list[i].Stop > list[i - 1].Stop, $"{group.Key} {list[i - 1]} → {list[i]}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void MomentumSellsAStockBelowItsAverageAtTheReview()
|
||||||
|
{
|
||||||
|
var data = Stocks(520, 0.001);
|
||||||
|
var friday = data.Sessions.Last(d => d.DayOfWeek == DayOfWeek.Friday && d < data.Sessions[^1]);
|
||||||
|
// S00 drifts down: it is below its 100-session average.
|
||||||
|
var bars = data["S00"]!.SeriesThrough(friday);
|
||||||
|
Assert.IsLessThan(Indicators.Sma(bars, 100)!.Value, bars.Close(bars.Count - 1));
|
||||||
|
var close = Math.Round((decimal)bars.Close(bars.Count - 1), 2);
|
||||||
|
var state = new PortfolioState(9_000m, new Dictionary<string, Holding> { ["S00"] = new(1_000m / close, close, null, friday.AddDays(-30)) });
|
||||||
|
var intent = BacktestEngine.DecideOnce(new EquityMomentum(), data, state, friday).Proposed.Single(i => i.Symbol == "S00");
|
||||||
|
Assert.AreEqual(0m, intent.TargetWeight);
|
||||||
|
Assert.IsTrue(intent.Reason is EquityMomentum.Reasons.ExitTrend or EquityMomentum.Reasons.ExitRank);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void EquityMomentumDoesNotLookAhead()
|
||||||
|
{
|
||||||
|
var data = Stocks(520, 0.001);
|
||||||
|
var result = LookAheadCheck.Run(_ => new EquityMomentum(), data);
|
||||||
|
Assert.IsTrue(result.Passed, string.Join("\n", result.Mismatches.Take(3)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- equity_meanrev ----
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 320 sessions rising by 0,1 a day from 72,3, then three falls of 1: every true range is 2 (high and low one away
|
||||||
|
/// from the close), so ATR(14) = 2 and the stop distance 2,5 × 2 = 5. RSI(2) ends near 1, the close (101) is below
|
||||||
|
/// its 5-session average and above its 200-session one.
|
||||||
|
/// </summary>
|
||||||
|
private static List<DailyBar> Dip(double shift = 0)
|
||||||
|
{
|
||||||
|
var closes = Enumerable.Range(0, 317).Select(i => Math.Round(72.3 + (0.1 * i), 1) + shift).Concat([103 + shift, 102 + shift, 101 + shift]).ToList();
|
||||||
|
return StrategyData.OnBusinessDays(StrategyData.FromCloses(closes, range: 1, volume: 100_000), Monday);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static BacktestDataset Shares(params (string Symbol, List<DailyBar> Bars)[] stocks) =>
|
||||||
|
new(stocks.Select(s => new BacktestInstrument(StrategyData.Share(s.Symbol), s.Bars)), "USD");
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void MeanrevSizesForARiskOfFourThousandthsCappedAtThirtyPercent()
|
||||||
|
{
|
||||||
|
var data = Shares(("AAA", Dip()));
|
||||||
|
var last = data.Sessions[^1];
|
||||||
|
|
||||||
|
// Reference equity = the strategy's 10.000 $: risk 40 $ over a 5 $ distance = 8 shares at 101 = 808 $, 8,08%.
|
||||||
|
var entry = BacktestEngine.DecideOnce(new EquityMeanrev(), data, PortfolioState.OnlyCash(10_000m), last).Proposed.Single();
|
||||||
|
Assert.AreEqual(EquityMeanrev.Reasons.Entry, entry.Reason);
|
||||||
|
Assert.AreEqual(0.0808m, entry.TargetWeight);
|
||||||
|
Assert.AreEqual(5m, entry.StopOffset);
|
||||||
|
|
||||||
|
// With the default share (15% of the bot) the reference is 66.666 $: 53,3 shares, more than the 30% cap.
|
||||||
|
var capped = BacktestEngine.DecideOnce(new EquityMeanrev(), data, PortfolioState.OnlyCash(10_000m), last, new BacktestOptions { ReferenceShare = 0.15m }).Proposed.Single();
|
||||||
|
Assert.AreEqual(0.3m, capped.TargetWeight);
|
||||||
|
|
||||||
|
// A position bought today holds 9.500 $, 500 $ stay free: not enough for the candidate (808 $), dropped.
|
||||||
|
var both = Shares(("AAA", Dip()), ("BBB", Dip()));
|
||||||
|
var poor = new PortfolioState(500m, new Dictionary<string, Holding> { ["BBB"] = new(9_500m / 101m, 101m, 96m, last) });
|
||||||
|
Assert.IsFalse(BacktestEngine.DecideOnce(new EquityMeanrev(), both, poor, last).Proposed.Any(i => i.Symbol == "AAA"));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void MeanrevTakesAtMostThreeWithTheLowestRsi()
|
||||||
|
{
|
||||||
|
// Five dips; a deeper last fall gives a lower RSI. The three deepest are chosen.
|
||||||
|
var stocks = Enumerable.Range(0, 5).Select(k =>
|
||||||
|
{
|
||||||
|
var bars = Dip(k);
|
||||||
|
bars[^1] = bars[^1] with { Close = bars[^1].Close - (0.1 * k), Low = bars[^1].Low - (0.1 * k) };
|
||||||
|
return ("D" + k.ToString(System.Globalization.CultureInfo.InvariantCulture), bars);
|
||||||
|
}).ToArray();
|
||||||
|
var data = Shares(stocks);
|
||||||
|
var intents = BacktestEngine.DecideOnce(new EquityMeanrev(), data, PortfolioState.OnlyCash(100_000m), data.Sessions[^1]).Proposed;
|
||||||
|
CollectionAssert.AreEqual(new[] { "D4", "D3", "D2" }, intents.Select(i => i.Symbol).ToArray());
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void MeanrevExitsAtTheCloseOnTheRules()
|
||||||
|
{
|
||||||
|
var bars = Dip();
|
||||||
|
var data = Shares(("AAA", bars));
|
||||||
|
var last = data.Sessions[^1];
|
||||||
|
Intent Exit(DateOnly entered, DateOnly day)
|
||||||
|
{
|
||||||
|
var state = new PortfolioState(9_000m, new Dictionary<string, Holding> { ["AAA"] = new(10m, 100m, 95m, entered) });
|
||||||
|
return BacktestEngine.DecideOnce(new EquityMeanrev(), data, state, day).Proposed.Single(i => i.Symbol == "AAA");
|
||||||
|
}
|
||||||
|
|
||||||
|
// In the rise the close is above its 5-session average: out at the close.
|
||||||
|
var rising = Exit(data.Sessions[^10], data.Sessions[^5]);
|
||||||
|
Assert.AreEqual(EquityMeanrev.Reasons.ExitAverage, rising.Reason);
|
||||||
|
Assert.IsTrue(rising.AtClose);
|
||||||
|
|
||||||
|
// In the dip none of the price rules says exit; held since the fifth session from the end: time is up.
|
||||||
|
var timed = Exit(data.Sessions[^5], last);
|
||||||
|
Assert.AreEqual(EquityMeanrev.Reasons.ExitTime, timed.Reason);
|
||||||
|
var state = new PortfolioState(9_000m, new Dictionary<string, Holding> { ["AAA"] = new(10m, 100m, 95m, data.Sessions[^4]) });
|
||||||
|
Assert.IsFalse(BacktestEngine.DecideOnce(new EquityMeanrev(), data, state, last).Proposed.Any(i => i.Symbol == "AAA"), "Four sessions: still held.");
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void EquityMeanrevDoesNotLookAhead()
|
||||||
|
{
|
||||||
|
var instruments = Enumerable.Range(0, 12).Select(k => new BacktestInstrument(StrategyData.Share("M" + k.ToString("00", System.Globalization.CultureInfo.InvariantCulture)),
|
||||||
|
StrategyData.OnBusinessDays([.. BacktestData.Walk(520, 300 + (ulong)k, start: 60 + k, drift: 0.0006, volatility: 0.02).Select(b => b with { Volume = 100_000 })], Monday)));
|
||||||
|
var data = new BacktestDataset(instruments, "USD");
|
||||||
|
var result = LookAheadCheck.Run(_ => new EquityMeanrev(), data);
|
||||||
|
Assert.IsTrue(result.Passed, string.Join("\n", result.Mismatches.Take(3)));
|
||||||
|
var run = BacktestEngine.Run(new EquityMeanrev(), data);
|
||||||
|
Assert.IsGreaterThan(5, run.Fills.Count, "The check must look at a strategy that trades.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Engine features the strategies need ----
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
[TestCategory(Category.Unit)]
|
||||||
|
public void AnExitAtTheCloseIsFilledAtThatCloseAndAStopOffsetFollowsThePriceObtained()
|
||||||
|
{
|
||||||
|
var d1 = BacktestData.D1;
|
||||||
|
var bars = new List<DailyBar>
|
||||||
|
{
|
||||||
|
new(d1, 100, 101, 99, 100, 1000),
|
||||||
|
new(d1.AddDays(1), 100, 102, 99, 101, 1000),
|
||||||
|
new(d1.AddDays(2), 101, 103, 100, 102, 1000),
|
||||||
|
new(d1.AddDays(3), 102, 103, 90, 95, 1000),
|
||||||
|
};
|
||||||
|
var script = new ScriptedStrategy(new Dictionary<DateOnly, IReadOnlyList<Intent>>
|
||||||
|
{
|
||||||
|
[d1] = [new Intent("BTC-EUR", 0.5m, "enter") { StopOffset = 5m }],
|
||||||
|
[d1.AddDays(2)] = [new Intent("BTC-EUR", 0m, "exit") { AtClose = true }],
|
||||||
|
});
|
||||||
|
var run = BacktestEngine.Run(script, BacktestData.One(BacktestData.Btc(), bars));
|
||||||
|
// Bought at the open of day 2 (100 + 5 bp → 100,1); sold at the close of day 3 itself, 102 − 5 bp → 101,9.
|
||||||
|
Assert.AreEqual(d1.AddDays(1), run.Fills[0].Day);
|
||||||
|
Assert.AreEqual(d1.AddDays(2), run.Fills[1].Day);
|
||||||
|
Assert.AreEqual(101.9m, run.Fills[1].Price);
|
||||||
|
Assert.AreEqual("exit", run.Fills[1].Reason);
|
||||||
|
|
||||||
|
// Without the exit, the stop sits 5 below the price obtained (95,1) and the low of day 4 (90) takes it.
|
||||||
|
var held = BacktestEngine.Run(new ScriptedStrategy(new Dictionary<DateOnly, IReadOnlyList<Intent>> { [d1] = [new Intent("BTC-EUR", 0.5m, "enter") { StopOffset = 5m }] }),
|
||||||
|
BacktestData.One(BacktestData.Btc(), bars));
|
||||||
|
var stop = held.Fills.Single(f => f.Side == OrderSide.Sell);
|
||||||
|
Assert.AreEqual(BacktestReasons.Stop, stop.Reason);
|
||||||
|
Assert.AreEqual(d1.AddDays(3), stop.Day);
|
||||||
|
Assert.AreEqual(95.0m, stop.Price);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Records the moment each decision is taken.</summary>
|
||||||
|
private sealed class Recording(IStrategy inner, List<DateTimeOffset> times) : IStrategy
|
||||||
|
{
|
||||||
|
public string Id => inner.Id;
|
||||||
|
|
||||||
|
public string Version => inner.Version;
|
||||||
|
|
||||||
|
public IReadOnlyList<DecisionTime> Schedule() => inner.Schedule();
|
||||||
|
|
||||||
|
public IReadOnlyList<string> Universe(UniverseContext context) => inner.Universe(context);
|
||||||
|
|
||||||
|
public IReadOnlyList<Intent> Decide(StrategyContext context)
|
||||||
|
{
|
||||||
|
times.Add(context.Now);
|
||||||
|
return inner.Decide(context);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user